Skip to content
Problem 1140 · LeetCode 1140(opens in a new tab)

Stone Game II

MediumDynamic programming

A row of stone piles lies on the table, piles[i] stones in pile i. Alice and Bob take turns, and Alice moves first. There is a number M, which starts at 1.

On a turn, the player takes the next X piles from the front of the row, for any X from 1 to 2M, and then M becomes the larger of M and X. The game ends when no piles are left. Both players play as well as possible, each trying to finish with more stones. Return how many stones Alice ends up with.

Example 1

Input:  piles = [3, 1, 5, 2]
Output: 5
Why:    Alice takes 3, Bob takes 1 and 5, Alice takes 2
2 more examples and the constraints

Example 2

Input:  piles = [2, 9, 4, 4, 7]
Output: 11
Why:    Alice takes 2 and 9, then Bob takes the last three piles

Example 3

Input:  piles = [8]
Output: 8
Why:    one pile, and Alice takes it

Constraints

  • 1 ≤ length of piles ≤ 100
  • 1 ≤ piles[i] ≤ 10,000

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Recursion + memoO(n³)
  2. Bottom-up tableO(n³)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 100 pilesVerdict
Recursion + memoO(n³)
Passes; easiest to derive
Bottom-up tableO(n³)
Best; no recursion, skips dead cells

n = number of piles.

Edge cases to test

  • One pile. [8]: Alice takes it, 8.
  • Two piles. With M = 1 Alice may take 2 piles, so she takes the whole row.
  • Big pile in the middle. [1, 100, 1]: Alice takes the first two and gets 101.
  • End in reach. Whenever i + 2M reaches the end, the mover takes everything; that is the base case.
  • Largest input. 100 piles of 10,000 stones total 1,000,000: fits in a 32-bit int.

Common mistakes

  • Letting M become x instead of max(M, x), so M can shrink.
  • Writing separate rules for Alice and Bob instead of using suffix[i] minus the other player's best.
  • Recursing without a memo, which explodes long before 100 piles.

How to talk through it

  1. 1Clarify. Do players take from the front only? Does M update to max(M, X)? Both play perfectly?
  2. 2Define the state. Position i and the current M fully describe the game left; the stones left are suffix[i].
  3. 3Write the rule. best(i, m) = max over x of suffix[i] − best(i + x, max(m, x)), with take-all as the base case.
  4. 4Memoize, then go bottom-up. n² states, up to 2m moves each: O(n³), fine for 100 piles.
  5. 5Test out loud. Run [3, 1, 5, 2] to show why taking two piles first loses.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?