Stone Game II (LeetCode 1140): Solution and Explanation

Medium
Array
Math
Dynamic Programming
Prefix Sum
Game Theory

Two players take 1 to 2M piles from the front of a row, and M grows to the largest take so far. Both play perfectly. Find how many stones Alice, who moves first, ends with.

Intuition

The whole game position is described by two numbers: the index i of the first pile still on the table and the current limit M. Who is to move does not matter, because both players use the same strategy.

The stones from index i to the end add up to a fixed total, suffix[i]. Every stone the opponent collects from the position you hand them is a stone you do not get, so your best score is suffix[i] minus the opponent's best score from that next position.

That turns the game into a DP: dp[i][M] = max over X of suffix[i] - dp[i + X][max(M, X)], filled from the end of the row backward.

Approach: Suffix-sum game DP over (i, M)

  1. Build suffix[i], the stones in piles i..n-1.
  2. Let dp[i][M] be the most stones the player to move can collect from pile i on with limit M.
  3. Fill i from n - 1 down to 0 and M from 1 to n.
  4. If i + 2M >= n, the player can take everything: dp[i][M] = suffix[i].
  5. Otherwise dp[i][M] = max(suffix[i] - dp[i + X][max(M, X)]) for X in 1..2M.
  6. Return dp[0][1].

Step-by-step example

piles = [2,7,9,4,4]
  1. Suffix sums are [26, 24, 17, 8, 4].
  2. Any state with i + 2M >= 5 takes everything, for example dp[3][1] = 8 and dp[2][2] = 17.
  3. dp[1][1]: take 1 leaves Bob dp[2][1] = 13, so 24 - 13 = 11. Take 2 leaves dp[3][2] = 8, so 24 - 8 = 16. dp[1][1] = 16.
  4. dp[0][1]: take X=1 gives 26 - dp[1][1] = 26 - 16 = 10. Take X=2 gives 26 - dp[2][2] = 26 - 17 = 9.
  5. The answer is 10: Alice takes [2], Bob takes [7,9], Alice takes [4,4].

Code: Python, Java, C++

1class Solution:
2    def stoneGameII(self, piles: List[int]) -> int:
3        n = len(piles)
4        suffix = [0] * (n + 1)
5        for i in range(n - 1, -1, -1):
6            suffix[i] = suffix[i + 1] + piles[i]
7        dp = [[0] * (n + 1) for _ in range(n + 1)]
8        for i in range(n - 1, -1, -1):
9            for m in range(1, n + 1):
10                if i + 2 * m >= n:
11                    dp[i][m] = suffix[i]
12                else:
13                    for x in range(1, 2 * m + 1):
14                        dp[i][m] = max(dp[i][m], suffix[i] - dp[i + x][max(m, x)])
15        return dp[0][1]
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n^3)

There are O(n^2) states (i, M) and each tries up to 2M moves.

Space

O(n^2)

The dp table has (n + 1) x (n + 1) entries. A memoised recursion only stores the states that are actually reachable, which is far fewer.

Other approaches

Memoised recursion (time O(n^3), space O(n^2))

Write best(i, M) recursively with a cache. It visits only reachable states and is the same recurrence top-down.

Minimax with two scores (time O(n^3), space O(n^2))

Track Alice's and Bob's totals separately with a turn flag. It works but doubles the state and is easy to get wrong; the suffix-sum trick removes the need.

Common mistakes

  • Forgetting that M becomes max(M, X), not X. M never shrinks.
  • Letting X run past the end of the row. The i + 2M >= n shortcut handles that case by taking everything.
  • Greedily grabbing the most stones now. In the example, taking two piles (9 stones) lets Bob take the remaining 17, which is worse than taking one pile.

Frequently asked questions

Why is there no separate DP for Bob?

The game is symmetric. From any (i, M) the player to move faces the same choices, so one table serves both players, and the opponent's score is read from the same table.

Why can M stop at n?

Once 2M is at least the number of remaining piles, any larger M changes nothing, so M values above n never need their own entry.

How does this differ from Stone Game?

In Stone Game players take one pile from either end. Here they take a growing number of piles from the front, so the state needs the limit M as well as the position.