1140. Stone Game II
Problem
Piles lie in a row; Alice and Bob alternate, Alice first, starting with M = 1. A player takes all stones from the first X remaining piles, with 1 ≤ X ≤ 2M, and then M becomes max(M, X). Both play optimally; return the most stones Alice can get.
Example: [2,7,9,4,4] → 10; [1,2,3,4,5,100] → 104
Constraints: up to 100 piles.
State (i, M): the player to move can take the next x ∈ [1, 2M] piles. With suffix sums, the stones this player ends with = suffix[i] − (what the opponent gets from (i + x, max(M, x))); maximize over x. If i + 2M ≥ n, take everything.
Complexity: O(n³) time, O(n²) states.
class Solution:
def stoneGameII(self, piles: List[int]) -> int:
n = len(piles)
suffix = list(itertools.accumulate(reversed(piles)))[::-1] + [0]
@cache
def best(i, m):
if i + 2 * m >= n:
return suffix[i]
return max(suffix[i] - best(i + x, max(m, x)) for x in range(1, 2 * m + 1))
return best(0, 1)
assert Solution().stoneGameII([2, 7, 9, 4, 4]) == 10
assert Solution().stoneGameII([1, 2, 3, 4, 5, 100]) == 104
assert Solution().stoneGameII([5]) == 5
class Solution {
public int stoneGameII(int[] piles) {
int n = piles.length;
int[] suffix = new int[n + 1];
for (int i = n - 1; i >= 0; i--) suffix[i] = suffix[i + 1] + piles[i];
int[][] dp = new int[n + 1][n + 1]; // dp[i][m]; M never exceeds n
for (int i = n - 1; i >= 0; i--) {
for (int m = 1; m <= n; m++) {
if (i + 2 * m >= n) { dp[i][m] = suffix[i]; continue; }
for (int x = 1; x <= 2 * m; x++) dp[i][m] = Math.max(dp[i][m], suffix[i] - dp[i + x][Math.max(m, x)]);
}
}
return dp[0][1];
}
}
func stoneGameII(piles []int) int {
n := len(piles)
suffix := make([]int, n+1) // stones in piles[i:]
for i := n - 1; i >= 0; i-- {
suffix[i] = suffix[i+1] + piles[i]
}
memo := map[[2]int]int{}
var best func(i, m int) int // most stones the player to move gets from piles[i:]
best = func(i, m int) int {
if i+2*m >= n {
return suffix[i] // take everything
}
key := [2]int{i, m}
if v, ok := memo[key]; ok {
return v
}
res := 0
for x := 1; x <= 2*m; x++ {
res = max(res, suffix[i]-best(i+x, max(m, x)))
}
memo[key] = res
return res
}
return best(0, 1)
}