Stone Game II solution explained
Stone Game II has two players take turns removing a prefix of the remaining piles: with a limit M that starts at 1, a player takes the next x piles for some x from 1 to 2M, and M becomes max(M, x). You must return the most stones the first player can collect if both play perfectly. Let best(i, M) be the most stones the player to move can get from piles i onward. Since the stones left always total suffix[i], best(i, M) is the maximum over x of suffix[i] - best(i + x, max(M, x)), and if 2M reaches the end the mover simply takes everything. That is O(n³) time over O(n²) states.
By Evin JohnPublished 8 min read
The problem, restated
Piles of stones stand in a row. Two players alternate, the first player moving first, and they share a number M that starts at 1. On a turn, the player takes all the stones in the first x piles that are still standing, where x is any value from 1 to 2M, and then M becomes the larger of M and x. The game ends when every pile is taken. Each player wants as many stones as possible. Return how many stones the first player ends with under best play from both sides.
| Piles | Total stones | First player gets |
|---|---|---|
| [10, 2, 2] | 14 | 12: take two piles, then the last pile goes to the other player |
| [3, 1, 4, 1, 5] | 14 | 8: take only the 3 first |
| [1, 2, 3, 4] | 10 | 5: a tie is the best available |
| [1, 9, 1, 1, 9] | 21 | 10 |
| [5] | 5 | 5 |
What the interviewer is checking
Stone Game II tests whether you can choose a state that captures everything the future depends on. The piles already taken do not matter, but the limit M does, because it controls how many piles the next player may grab. Interviewers listen for the pair (i, M), for the suffix-sum trick that turns "my stones" into "everything left minus what the opponent will get", and for the end condition that lets the mover sweep the rest. They may also ask why M can be capped.
Questions worth asking
- Does M change for both players? Yes, it is shared, and it only grows.
- Must a player take at least one pile? Yes, x is at least 1.
- Is a pile ever split? No, piles are taken whole, in order from the front.
Brute force: play out every game
The direct approach simulates the game tree: at each turn, try every allowed x, let the opponent respond with every allowed move, and keep the line of play that is best for whoever is moving. With up to 2M choices per turn and M growing, the tree explodes quickly, yet many branches reach the same pair of remaining piles and current limit. That repetition is exactly what memoization removes. The tests for this page used the full game tree, without any caching, as the reference for rows of up to 10 piles.
Why grabbing the most piles is not safe
Taking more piles now also raises M, which hands the opponent a bigger move. On [3, 1, 4, 1, 5], taking two piles gives the first player 4 stones but sets M to 2, so the opponent may take up to four piles, which is all of the remaining 10. Taking a single pile keeps M at 1 and leads to 8 stones for the first player. Any greedy rule about size or value fails on rows like this, which is why the problem needs a search over moves.
The recurrence
Let suffix[i] be the total of piles i to n - 1. On state (i, M), whatever the mover does not collect, the opponent collects, because the two totals always add up to suffix[i]. If the mover takes x piles, the opponent then plays the state (i + x, max(M, x)) and collects best(i + x, max(M, x)). Everything else on the table goes to the mover. So the mover's total for that move is suffix[i] - best(i + x, max(M, x)), and the mover picks the x that maximizes it. If i + 2M >= n, the mover can take every remaining pile in one move, and that is clearly best.
from functools import lru_cache
def stone_game_ii(piles):
n = len(piles)
suffix = [0] * (n + 1)
for i in range(n - 1, -1, -1):
suffix[i] = suffix[i + 1] + piles[i]
@lru_cache(maxsize=None)
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)Taking all remaining piles is only checked through the base case. When i + 2M is below n, every allowed x leaves at least one pile, so best(i + x, ...) is always called on a non-empty suffix.
Bottom-up table
best(i, M) depends only on states with a larger i, so fill i from n - 1 down to 0. M ranges from 1 to n: once 2M reaches the number of remaining piles, larger values of M give the same answer, so capping at n loses nothing. Using max(m, x) as a column index never goes past n because x is at most 2M and is only used while i + x is still below n.
def stone_game_ii_table(piles):
n = len(piles)
suffix = [0] * (n + 1)
for i in range(n - 1, -1, -1):
suffix[i] = suffix[i + 1] + piles[i]
table = [[0] * (n + 1) for _ in range(n + 1)]
for i in range(n - 1, -1, -1):
for m in range(1, n + 1):
if i + 2 * m >= n:
table[i][m] = suffix[i]
continue
rival = min(table[i + x][max(m, x)] for x in range(1, 2 * m + 1))
table[i][m] = suffix[i] - rival
return table[0][1]function stoneGameII(piles) {
const n = piles.length;
const suffix = new Array(n + 1).fill(0);
for (let i = n - 1; i >= 0; i--) suffix[i] = suffix[i + 1] + piles[i];
const table = Array.from({ length: n + 1 }, () => new Array(n + 1).fill(0));
for (let i = n - 1; i >= 0; i--) {
for (let m = 1; m <= n; m++) {
if (i + 2 * m >= n) {
table[i][m] = suffix[i];
continue;
}
let rival = Infinity;
for (let x = 1; x <= 2 * m; x++) {
rival = Math.min(rival, table[i + x][Math.max(m, x)]);
}
table[i][m] = suffix[i] - rival;
}
}
return table[0][1];
}Trace on [10, 2, 2]
suffix is [14, 4, 2, 0]. From (2, 1), one pile is left and the mover takes it: 2. From (1, 1), two piles are left and 2M = 2 reaches the end, so the mover takes both: 4. From (0, 1), the choices are x = 1, giving 14 - best(1, 1) = 14 - 4 = 10, or x = 2, giving 14 - best(2, 2) = 14 - 2 = 12. The first player takes two piles and finishes with 12.
Complexity
| Approach | Time | Extra memory |
|---|---|---|
| Try every move sequence | Exponential | O(n) stack |
| Memoized search over (i, M) | O(n³) | O(n²) |
| Bottom-up table | O(n³) | O(n²) |
The cube is loose in practice, because the base case cuts off every state where 2M already reaches the end, and that covers most large values of M.
Edge cases
- One or two piles: the first player takes them all, since 2M = 2.
- Equal piles: the result often splits the total evenly or close to it.
- A very large pile deep in the row, where the timing of M growth decides who reaches it.
- Rows where the best first move is a single pile even though two are allowed, as in [3, 1, 4, 1, 5].
Common mistakes
- Leaving M out of the state, which gives wrong answers as soon as move sizes differ.
- Tracking whose turn it is and both totals, instead of the suffix-sum difference.
- Updating M to x instead of max(M, x), which lets the limit shrink.
- Forgetting the take-everything base case and looping past the end of the row.
- Sizing the table by 2n columns for M without need; n is enough.
How to explain it out loud
Fictional example
- Candidate
- What is left of the game is decided by two things: where the remaining piles start, and the current M. So my state is (i, M), and its value is the most stones the player to move can still collect.
- Candidate
- All remaining stones end up with one of the two players, so if I take x piles and the opponent then gets their best from (i + x, max(M, x)), I get the suffix total minus that. I try every x up to 2M.
- Interviewer
- When can you stop early?
- Candidate
- If 2M covers everything that is left, the mover takes it all. That base case also means M never needs to go above n.
Related problems
Predict the Winner is the simpler game where each turn takes one number from either end, and it uses the same subtract-the-opponent idea on a score difference. Minimum Cost Tree From Leaf Values and Guess Number Higher or Lower II are interval DPs where each state tries every split point, which has the same cubic shape. Uncrossed Lines is a two-index table worth comparing with this index-and-limit one.
Practicing with Natively
The hardest step is saying why M belongs in the state, so practice that sentence until it is crisp. In a mock round on Mac or Windows, Natively transcribes what you say, which lets you check later whether the state came before the code. Once you have worked through the problem yourself, Natively can read it from a screenshot and suggest an approach to compare with yours. Read about the AI interview assistant.
Questions people ask
How do you solve Stone Game II?
Let best(i, M) be the most stones the player to move can collect from pile i on. It is the max over x from 1 to 2M of suffix[i] - best(i + x, max(M, x)), and simply suffix[i] when i + 2M reaches the end. The answer is best(0, 1).
Why is M part of the state in Stone Game II?
M decides how many piles the next player may take, so two positions with the same remaining piles but different M can have different outcomes.
What is the time complexity of Stone Game II?
O(n cubed) time and O(n squared) memory: M never needs to exceed n, giving O(n squared) states, each trying up to 2M moves.
Is taking the most piles allowed always best?
No. Taking more piles raises M for the opponent. On [3, 1, 4, 1, 5], taking two piles first gives 4 stones, while taking one gives 8.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
