Alice and Bob continue their games with piles of stones. There are a number of piles arranged in a row, and each pile has a positive integer number of stones piles[i]
. The objective of the game is to end with the most stones.
Alice and Bob take turns, with Alice starting first. Initially, M = 1
.
On each player’s turn, that player can take all the stones in the first X
remaining piles, where 1 <= X <= 2M
. Then, we set M = max(M, X)
.
The game continues until all the stones have been taken.
Assuming Alice and Bob play optimally, return the maximum number of stones Alice can get.
Example
Input: piles = [2,7,9,4,4]
Output: 10
Explanation: If Alice takes one pile at the beginning, Bob takes two piles, then Alice takes 2 piles again. Alice can get 2 + 4 + 4 = 10 piles in total. If Alice takes two piles at the beginning, then Bob can take all three piles left. In this case, Alice get 2 + 7 = 9 piles in total. So we return 10 since it's larger.
Solution
/**
* @param {number[]} piles
* @return {number}
*/
var stoneGameII = function (piles) {
let n = piles.length;
//dp[i][m] means the maximum number of stones that the current player can get when the current player is playing piles[i:] and the current M is m
let dp = new Array(n + 1).fill(0).map(() => new Array(n + 1).fill(0));
//sum[i] means the sum of piles[i:]
let sum = new Array(n + 1).fill(0);
for (let i = n - 1; i >= 0; i--) {
//the sum index is equal to the sum of piles[i:] plus the sum of piles[i + 1:]
sum[i] = sum[i + 1] + piles[i];
}
for (let i = n - 1; i >= 0; i--) {
for (let m = 1; m <= n; m++) {
//if i + 2 * m is greater than or equal to n, then the current player can take all the remaining piles
if (i + 2 * m >= n) {
dp[i][m] = sum[i];
} else {
for (let x = 1; x <= 2 * m; x++) {
//the current player can take x piles, then the next player can take dp[i + x][Math.max(m, x)] piles
dp[i][m] = Math.max(dp[i][m], sum[i] - dp[i + x][Math.max(m, x)]);
}
}
}
}
return dp[0][1];
};