There are n
coins in a line, and value of i-th
coin is values[i]
.
Two players take turns to take a coin from one of the ends of the line until there are no more coins left. The player with the larger amount of money wins.
Could you please decide the first player will win or lose?
Example
Example 1:
Input: [3, 2, 2]
Output: true
Explanation: The first player takes 3 at first. Then they both take 2.
Example 2:
Input: [1, 20, 4]
Output: false
Explanation: The second player will take 20 whether the first player take 1 or 4.
Challenge
O(1) memory and O(n) time when n
is even.
思路:跟Coins in a Line II,一样,转移方程考虑减去对手能够取得的最大值,f[i][j] 表示面对i~j的coins,我能得到的最大的与对手的数字差;
f[i][j] = Math.max(A[i] - f[i+1][j], A[j] - f[i][j-1]); 初始值f[i][i] = A[i]; 区间型动态规划,从len开始循环,枚举start index i,然后枚举所有的k,最后判断f[0][n-1] >=0; 用len做为外循环,模板走起;初始值f[i][i] = A[i]; 区间+博弈;
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[] A) {
if(A == null || A.length == 0) {
return false;
}
int n = A.length;
int[][] f = new int[n][n];
// f[i][j]表示,面对i ~ j的coins,能够取得的最大值;
for(int i = 0; i < n; i++) {
f[i][i] = A[i];
}
// f[i][j] = Math.max(A[i-1] - f[i+1][j], A[j-1] - f[i][j+1]);
for(int len = 2; len <= n; len++) {
for(int i = 0; i + len - 1 < n; i++) {
int j = i + len - 1;
f[i][j] = Math.max(A[i] - f[i + 1][j], A[j] - f[i][j - 1]);
}
}
return f[0][n - 1] >= 0;
}
}