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

Stone Game

MediumDynamic programming

Alice and Bob face a row of piles of stones, piles[i] stones in pile i. The number of piles is even, and the total number of stones is odd, so a draw is impossible.

They take turns, Alice first. On a turn, a player removes a whole pile from either the left end or the right end of the row and keeps it. When no piles are left, whoever holds more stones wins.

If both play as well as possible, return true when Alice wins and false when Bob wins.

Example 1

Input:  piles = [2,6,3,2]
Output: true
Why:    Alice can take both odd positions, 6 + 2 = 8 against 5
2 more examples and the constraints

Example 2

Input:  piles = [9,2]
Output: true
Why:    Alice takes 9 and Bob gets 2

Example 3

Input:  piles = [1,8,2,7,4,3]
Output: true
Why:    the odd positions hold 18 of the 25 stones

Constraints

  • 2 ≤ length of piles ≤ 500, and the length is even
  • 1 ≤ piles[i] ≤ 500
  • The sum of all piles is odd

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. Minimax with memoO(n²)
  2. Bottom-up tableO(n²)
  3. Even or odd positionsO(1)

The idea in one sentence

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

Side by side

ApproachTimeRelative work for 500 pilesVerdict
Minimax with memoO(n²)
Passes; works for any row
Bottom-up tableO(n²)
Passes; no recursion
Even or odd positionsO(1)
Best; relies on even count, odd total

n = number of piles.

Edge cases to test

  • Two piles. Alice takes the bigger one; they cannot be equal because the total is odd.
  • Greedy fails. In [3,9,1,2], taking the bigger end, 3, lets Bob take 9. Alice must take 2 first, and then the 9 is hers.
  • Big pile in the middle. [1,100,1,1]: Alice takes a 1 at the right end so that Bob cannot reach the 100 first.
  • Largest input. 500 piles is 125,250 ranges for the DP, which is still fast.

Common mistakes

  • Playing greedily, always taking the bigger end, which can hand the opponent a large pile.
  • Tracking only Alice's score in the DP and forgetting that Bob also plays to win.
  • Giving return true with no reason; the interviewer wants the colour argument.

How to talk through it

  1. 1Clarify. Is the number of piles always even and the total always odd? Can only the ends be taken?
  2. 2Model it. Let lead(i, j) be the best lead of the player to move; the opponent's lead is subtracted.
  3. 3Code the DP. Memo or table over all ranges, O(n²), then check lead(0, n − 1) > 0.
  4. 4Spot the shortcut. Colour even and odd positions; Alice can force a whole colour, so she always wins.
  5. 5Test out loud. Run two piles and [1,100,1,1], where the middle pile must be protected.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?