There are n coins with different value in a line. Two players take turns to take one or two coins from left side until there are no more coins left. The player who take the coins with the most value wins.
Could you please decide the first player will win or lose?
Example
此题同样适用DP。res[i]代表从i到最后能取到的最大值。公式为:
Given values array A = [1,2,2]
, return true
.
Given A = [1,2,4]
, return false
.
res[i] = max(values[i] + min(res[i + 2], res[i + 3]), values[i] + min(res[i + 3], res[i + 4]))
第一种情况是后手取i+1,第二种情况是后手取i+1和i+2. 后手每次也是尽量取尽可能大的value,所以要在剩下的values中取最小的。如果题目改成问先手是否有可能赢,那么此处可以使用max。即为后手失误取最小值的情况。
public class Solution {
/**
* @param values: an array of integers
* @return: a boolean which equals to true if the first player will win
*/
public boolean firstWillWin(int[] values) {
if(values.length <= 2) return true;
if(values.length < 4) {
return values[0] + values[1] > values[2];
}
int total = values[values.length - 1] + values[values.length - 2];
int[] res = new int[values.length];
res[values.length - 1] = values[values.length - 1];
res[values.length - 2] = values[values.length - 2] + values[values.length - 1];
for(int i = values.length - 3; i >= 0; i--) {
total += values[i];
int pos3 = i + 3 >= values.length ? 0 : res[i + 3];
int pos4 = i + 4 >= values.length ? 0 : res[i + 4];
int first = values[i] + Math.min(res[i + 2], pos3);
int second = values[i] + values[i + 1] + Math.min(pos3, pos4);
res[i] = Math.max(first, second);
}
int second = total - res[0];
return res[0] > second;
}
}