Stone Game II
Hard
Topics
Alice and Bob play with piles of stones nums (pile i has nums[i] stones). Alice moves first with M = 1. On a turn a player takes all stones from the first X remaining piles where 1 <= X <= 2M, then M becomes max(M, X). Both play optimally to maximize their own stones. Return the maximum stones Alice can collect.
Example 1
Input: nums = [2,7,9,4,4] Output: 10
Example 2
Input: nums = [1,2,3,4,5,100] Output: 104
Constraints
- 1 <= nums.length <= 100
- 1 <= nums[i] <= 10^4
Editorial — intuition, approach, complexity and pitfalls
Intuition
The state is where the row starts and how large the current M is, because those two facts determine every legal move. dp[i][m] is the most the player to move can secure from piles[i:] with parameter m.
The trick that keeps this manageable is the suffix sum. Rather than tracking both players' totals, note that whatever the opponent secures from the remaining suffix, the current player gets the rest: dp[i][m] = suffix[i] - dp[i+X][max(m, X)], maximised over X in 1..2m. The subtraction is the turn change, same device as predict the winner.
The base case is the shortcut: if i + 2m >= n the player can simply take everything left, so dp[i][m] = suffix[i].
Approach
- Build suffix sums.
- Fill
dpbackwards overi, for everym. - If
i + 2mcovers the rest, the answer is the whole suffix. - Otherwise maximise
suffix[i] - dp[i+X][max(m, X)]overXin1..2m. - Return
dp[0][1].
Dry Run
piles = [2,7,9,4,4]
suffix sums [26, 24, 17, 8, 4, 0]
at i = 0 with m = 1 the player may take 1 or 2 piles
X = 1 take [2] opponent then faces i=1, m=1
X = 2 take [2,7] opponent then faces i=2, m=2
each branch is scored as suffix[0] - dp[next state], so the player picks the
branch that leaves the opponent least
answer 10
Alice ends with 10 of the 26 stones -- taking greedily from the front does not
help, because a large X raises M and hands the opponent a bigger move.Complexity
- Time — O(n³): there are O(n²) states, since
mnever usefully exceedsn, and each tries O(n) values ofX. At the stated bound of 100 piles that is about 10⁶ operations. - Space — O(n²) for the table. The
mdimension is capped at2n + 2because once2mcovers the rest of the row the base case fires.
Common Pitfalls
- Tracking both players' scores. The suffix-minus-opponent formulation removes a whole dimension.
- Forgetting that
Mbecomesmax(M, X)and not simplyX. Taking a smallXdoes not shrink the allowance. - Bounding
matnrather than something above2n.max(m, X)withXup to2mcan push the index pastn, so the table needs the headroom — the shown code allocates2n + 2. - Returning
dp[0][0]. The game starts withM = 1. - Playing greedily, taking the largest immediate haul. A big
XraisesMand gives the opponent a larger move, which is exactly the tension the DP resolves. - Filling the table forwards.
dp[i][m]depends on largeri, so the sweep must go backwards.
Full Solution — all languages
class Solution:
def stoneGameII(self, nums):
piles = nums
n = len(piles)
suf = [0] * (n + 1)
for i in range(n - 1, -1, -1):
suf[i] = suf[i + 1] + piles[i]
M = 2 * n + 2
dp = [[0] * M for _ in range(n + 1)]
for i in range(n - 1, -1, -1):
for m in range(1, M):
if i + 2 * m >= n:
dp[i][m] = suf[i]
else:
best = 0
for x in range(1, 2 * m + 1):
mm = m if m > x else x
val = suf[i] - dp[i + x][mm]
if val > best:
best = val
dp[i][m] = best
return dp[0][1]import java.util.*;
class Solution {
public int stoneGameII(int[] nums) {
int[] piles = nums;
int n = piles.length;
long[] suf = new long[n + 1];
for (int i = n - 1; i >= 0; i--) suf[i] = suf[i + 1] + piles[i];
int M = 2 * n + 2;
long[][] dp = new long[n + 1][M];
for (int i = n - 1; i >= 0; i--) {
for (int m = 1; m < M; m++) {
if (i + 2 * m >= n) dp[i][m] = suf[i];
else {
long best = 0;
for (int x = 1; x <= 2 * m; x++) {
int mm = m > x ? m : x;
long val = suf[i] - dp[i + x][mm];
if (val > best) best = val;
}
dp[i][m] = best;
}
}
}
return (int) dp[0][1];
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int stoneGameII(vector<int>& nums) {
vector<int>& piles = nums;
int n = piles.size();
vector<long long> suf(n + 1, 0);
for (int i = n - 1; i >= 0; i--) suf[i] = suf[i + 1] + piles[i];
int M = 2 * n + 2;
vector<vector<long long>> dp(n + 1, vector<long long>(M, 0));
for (int i = n - 1; i >= 0; i--) {
for (int m = 1; m < M; m++) {
if (i + 2 * m >= n) dp[i][m] = suf[i];
else {
long long best = 0;
for (int x = 1; x <= 2 * m; x++) {
int mm = m > x ? m : x;
long long val = suf[i] - dp[i + x][mm];
if (val > best) best = val;
}
dp[i][m] = best;
}
}
}
return (int)dp[0][1];
}
};/**
* @param {number[]} nums
* @return {number}
*/ var stoneGameII = function(nums) {
const piles = nums, n = piles.length;
const suf = new Array(n + 1).fill(0);
for (let i = n - 1; i >= 0; i--) suf[i] = suf[i + 1] + piles[i];
const M = 2 * n + 2;
const dp = [];
for (let i = 0; i <= n; i++) dp.push(new Array(M).fill(0));
for (let i = n - 1; i >= 0; i--) {
for (let m = 1; m < M; m++) {
if (i + 2 * m >= n) dp[i][m] = suf[i];
else {
let best = 0;
for (let x = 1; x <= 2 * m; x++) {
const mm = m > x ? m : x;
const val = suf[i] - dp[i + x][mm];
if (val > best) best = val;
}
dp[i][m] = best;
}
}
}
return dp[0][1];
};