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

Stone Game III

HardDynamic programming

Stones lie in a row, and stone i is worth stoneValue[i] points, which may be negative. Alice and Bob take turns, Alice first. On a turn, the player removes the first 1, 2 or 3 stones still in the row and adds their values to their own score. Both start at 0, and the game ends when the row is empty.

Both players always make the best possible move. Return "Alice" if Alice ends with more points, "Bob" if Bob does, and "Tie" if their scores are equal.

Example 1

Input:  stoneValue = [2, -1, 4, 3]
Output: "Alice"
Why:    Alice takes 2, -1, 4 for 5 points; Bob gets the 3
2 more examples and the constraints

Example 2

Input:  stoneValue = [1, 1, 1, 5]
Output: "Bob"
Why:    whatever Alice takes, Bob can reach the 5

Example 3

Input:  stoneValue = [-3, 1, 4, 2]
Output: "Tie"
Why:    Alice takes all but the 2 for 2 points; Bob gets 2

Constraints

  • 1 ≤ stoneValue.length ≤ 50,000
  • −1,000 ≤ stoneValue[i] ≤ 1,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. Minimax with a memoO(n)
  2. Bottom-up DPO(n)

The idea in one sentence

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

Side by side

ApproachTimeRelative work for 50,000 stonesVerdict
Minimax with a memoO(n)
Passes; deep recursion
Bottom-up DPO(n)
Best; a single loop

n = number of stones.

Edge cases to test

  • One stone. Alice must take it: positive wins, negative loses, zero ties.
  • Every value negative. Taking fewer stones can be the best move; the lead can be negative.
  • Fewer than three stones left. Only try takes that stay inside the row.
  • Greedy is wrong. Grabbing the biggest sum now can hand the opponent a better row; always subtract their lead.

Common mistakes

  • Starting the best value at 0 instead of minus infinity, which wrongly allows taking no stones.
  • Adding the opponent's lead instead of subtracting it.
  • Tracking Alice's and Bob's scores separately and mixing up whose turn it is.

How to talk through it

  1. 1Clarify. Can values be negative? Must a player take at least one stone? What do I return on equal scores?
  2. 2Use one number. The mover's lead over the other player, so both turns use the same formula.
  3. 3Write the recurrence. lead(i) = best of sum of k stones minus lead(i + k), for k = 1, 2, 3.
  4. 4Go bottom-up. Fill from the right to avoid 50,000-deep recursion; mention the three-variable version.
  5. 5Test out loud. Run a single negative stone and an all-negative row before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?