Stone Game III (LeetCode 1406): Solution and Explanation

Hard
Array
Math
Dynamic Programming
Game Theory

Stones with possibly negative values sit in a row. Alice and Bob alternate, Alice first, each taking 1, 2 or 3 stones from the front. With optimal play, return "Alice", "Bob" or "Tie".

Intuition

Once some stones are gone, the rest of the game only depends on where the row now starts. The player to move faces exactly the same choices whether they are Alice or Bob, so one number per position is enough.

Store dp[i] = the score of the player to move minus the score of the other player, when stones i..n-1 remain and both play optimally. With no stones left nobody scores, so dp[n] = 0.

If you take k stones you gain their sum. Then the opponent is the player to move at i + k and ends up dp[i + k] ahead of you on the rest. Your total lead is take - dp[i + k], and you pick the k that makes it largest.

Negative stones are the trap: sometimes taking more stones is right because it leaves a bad stone for the opponent, and sometimes taking one stone is right because the next ones are negative. The max over all three choices handles both.

Approach: Score-difference DP from the back

  1. Create dp of length n + 1 filled with 0. dp[n] = 0 is the empty row.
  2. For i from n - 1 down to 0, keep a running sum take and try k = i, i + 1, i + 2 (while k < n).
  3. For each, add stoneValue[k] to take and compute take - dp[k + 1]. Keep the largest as dp[i].
  4. dp[0] is Alice's lead. Return "Alice" if it is positive, "Bob" if negative, "Tie" if zero.

Step-by-step example

stoneValue = [1, 2, 3, 7]
  1. dp[4] = 0. At i = 3 the only move takes 7: dp[3] = 7.
  2. i = 2: take 3 gives 3 - 7 = -4; take 3 + 7 = 10 gives 10 - 0 = 10. dp[2] = 10.
  3. i = 1: take 2 gives 2 - 10 = -8; take 5 gives 5 - 7 = -2; take 12 gives 12 - 0 = 12. dp[1] = 12.
  4. i = 0: take 1 gives 1 - 12 = -11; take 3 gives 3 - 10 = -7; take 6 gives 6 - 7 = -1. dp[0] = -1, so Bob wins.

Code: Python, Java, C++

1class Solution:
2    def stoneGameIII(self, stoneValue: List[int]) -> str:
3        n = len(stoneValue)
4        dp = [0] * (n + 1)
5        for i in range(n - 1, -1, -1):
6            best = float('-inf')
7            take = 0
8            for k in range(i, min(i + 3, n)):
9                take += stoneValue[k]
10                best = max(best, take - dp[k + 1])
11            dp[i] = best
12        return "Alice" if dp[0] > 0 else "Bob" if dp[0] < 0 else "Tie"
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

Each position tries at most three moves.

Space

O(n)

The dp array has n + 1 entries. Only the next three values are ever read, so it can be cut to O(1).

Other approaches

Three rolling values (time O(n), space O(1))

dp[i] only reads dp[i + 1], dp[i + 2] and dp[i + 3], so keep those three numbers instead of the array.

Track both scores with suffix sums (time O(n), space O(n))

Let best[i] be the most the player to move can collect from i onward. The opponent then collects suffix[i] - best[i], so best[i] = suffix[i] - min(best[i + k]). Compare best[0] with suffix[0] - best[0].

Memoized minimax recursion (time O(n), space O(n))

Recurse on the start position with the same take - next rule and cache the result. It is the same DP top down, but n = 5 * 10^4 can exceed the default recursion limit.

Common mistakes

  • Initializing the best move to 0 instead of negative infinity. With negative stones every move can be a loss, and you must still pick one.
  • Greedily taking the most valuable prefix. A large take can hand the opponent an even better position.
  • Running past the end of the array: only take k stones when at least k remain.
  • Storing two scores per position and alternating the player. One difference value per position is enough because the game is zero sum.

Frequently asked questions

Why does dp not need to know whose turn it is?

Both players have the same moves and the same goal (maximize their own lead), so the best lead from position i is the same for whoever is to move.

Why subtract dp[i + k] instead of adding?

After your move the opponent moves first on the rest and finishes dp[i + k] ahead of you there. Their lead is your deficit, so it is subtracted from what you just took.

How does this differ from Stone Game II?

Stone Game II lets the number of piles you may take grow with M, so the state needs (i, M). Here the limit is always 3, so the state is just i and the DP is linear.