Stone Game II

Hard

Topics
ArrayMathDynamic ProgrammingGame Theory

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

2071924344
Input:  nums = [2,7,9,4,4]
Output: 10

Example 2

10213243541005
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

  1. Build suffix sums.
  2. Fill dp backwards over i, for every m.
  3. If i + 2m covers the rest, the answer is the whole suffix.
  4. Otherwise maximise suffix[i] - dp[i+X][max(m, X)] over X in 1..2m.
  5. 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 m never usefully exceeds n, and each tries O(n) values of X. At the stated bound of 100 piles that is about 10⁶ operations.
  • Space — O(n²) for the table. The m dimension is capped at 2n + 2 because once 2m covers 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 M becomes max(M, X) and not simply X. Taking a small X does not shrink the allowance.
  • Bounding m at n rather than something above 2n. max(m, X) with X up to 2m can push the index past n, so the table needs the headroom — the shown code allocates 2n + 2.
  • Returning dp[0][0]. The game starts with M = 1.
  • Playing greedily, taking the largest immediate haul. A big X raises M and gives the opponent a larger move, which is exactly the tension the DP resolves.
  • Filling the table forwards. dp[i][m] depends on larger i, 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]
SensAI
Beta
Tap the mic to stop voice mode