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?
If the first player wins, return true
, otherwise return false
.
Example
Example 1:
Input: [1, 2, 2]
Output: true
Explanation: The first player takes 2 coins.
Example 2:
Input: [1, 2, 4]
Output: false
Explanation: Whether the first player takes 1 coin or 2, the second player will gain more value.
思路:这题关键点在于, f[i] 表示的是面对[i...n-1] 的数字的时候,我能够取得的最大值,这里可以取一个,或者取两个;
f[i] = Math.max(a[i] - f[i+1], a[i] + a[i+1] - f[i+2]) ;
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 == null || values.length == 0) {
return false;
}
int n = values.length;
int[] dp = new int[n + 1];
dp[n] = 0;
// dp[i] 表示面对i ~ n-1 的coin,能拿的最大value;
for(int i = n - 1; i >= 0; i--) {
dp[i] = values[i] - dp[i + 1];
if(i + 2 <= n) {
dp[i] = Math.max(dp[i], values[i] + values[i + 1] - dp[i + 2]);
}
}
return dp[0] >= 0;
}
}