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
Given values array A = [1,2,2], return true.
Given A = [1,2,4], return false.
public class Solution {
/**
* @param values: a vector of integers
* @return: a boolean which equals to true if the first player will win
*/
public boolean firstWillWin(int[] values) {
if (values.length == 0) return false;
else if (values.length < 3) return true;
int N = values.length;
int dp[] = new int[values.length + 2];
dp[N - 1] = values[N - 1];
dp[N - 2] = values[N - 1] + values[N - 2];
for (int i = N - 3; i >= 0; --i) {
int get1 = values[i] + Math.min(dp[i + 2], dp[i + 3]);
int get2 = values[i] + values[i + 1] + Math.min(dp[i + 3], dp[i + 4]);
dp[i] = Math.max(get1, get2);
}
int sum = 0;
for (int val : values) sum += val;
return dp[0] > sum / 2;
}
}