Stone Game

Medium

Topics
ArrayDynamic ProgrammingGame TheoryMath

Alice and Bob play a game with piles of stones arranged in a row. The i-th pile has piles[i] stones, and the total number of stones across all piles is odd.

On each turn a player takes the entire pile from either end of the row. The game ends when there are no piles left, and the player with the most stones wins.

Assuming both players play optimally, return true if Alice (who moves first) wins.

Example 1

50314253
Input:  piles = [5,3,4,5]
Output: true
Explanation: Alice takes the first pile (5). Whatever Bob does, Alice can take the last remaining 5 and finish with at least 10 of the 17 stones.

Example 2

30712233
Input:  piles = [3,7,2,3]
Output: true

Constraints

  • 2 <= piles.length <= 500
  • piles.length is even
  • 1 <= piles[i] <= 500
  • sum(piles[i]) is odd
Editorial — intuition, approach, complexity and pitfalls

Intuition

Track the score difference rather than two separate totals. If dp[i][j] is the best margin the player to move can force on the subarray piles[i..j], then taking one end hands the opponent the rest, and their best margin counts against you. That single sign flip turns a two-player minimax into a plain maximisation. Alice wins exactly when the margin over the whole row is positive.

Approach

  1. Let dp[i][j] be the maximum (current player's stones - opponent's stones) achievable on piles[i..j].
  2. Base case: dp[i][i] = piles[i], since a single pile goes entirely to the player to move.
  3. Recurrence: dp[i][j] = max(piles[i] - dp[i+1][j], piles[j] - dp[i][j-1]). Subtracting the subproblem is what encodes "the opponent now moves optimally against me".
  4. Fill by increasing length so both smaller ranges are ready, then return dp[0][n-1] > 0.
  5. There is also a one-line answer: with an even pile count Alice can commit to taking every even-indexed pile or every odd-indexed pile, and one of those groups has the larger sum, so she always wins. Interviewers usually want the proof and the DP.
class Solution:
    def stoneGame(self, piles):
        n = len(piles)
        dp = [[0] * n for _ in range(n)]
        for i in range(n):
            dp[i][i] = piles[i]
        for length in range(2, n + 1):
            for i in range(n - length + 1):
                j = i + length - 1
                dp[i][j] = max(piles[i] - dp[i + 1][j], piles[j] - dp[i][j - 1])
        return dp[0][n - 1] > 0

Dry Run

piles [5, 3, 4, 5].  dp[i] is a MARGIN -- how far ahead the player to move can get
on the subarray -- not a score. One number per state instead of two.
  length 1   dp = [5, 3, 4, 5]        a single pile is the whole margin
  length 2   [5,3] -> max(5-3, 3-5) = 2
             [3,4] -> max(3-4, 4-3) = 1
             [4,5] -> max(4-5, 5-4) = 1
             dp = [2, 1, 1, 5]
  length 3   [5,3,4] -> max(5-1, 4-2) = 4
             [3,4,5] -> max(3-1, 5-1) = 4
             dp = [4, 4, 1, 5]
  length 4   max(5-4, 5-4) = 1
             dp = [1, 4, 1, 5]
answer dp[0] = 1 > 0, so true
The subtraction is what makes the game adversarial. `nums[i] - dp[i+1]` says "I
take the left pile, and then my opponent gets the best margin on what remains, so
their gain is my loss". Replace the minus with a plus and you have modelled a
cooperative game: the margin for [5,3,4,5] becomes 17, which is simply the total
of all piles.
Being precise about that bug is worth it, because on this problem it cannot be
caught by any valid test. The constraints fix an even pile count and an odd total,
and under those the first player always wins -- the shipped answer is true for
every legal input, and so is the plus version. Across every even-length, odd-sum
input over small piles, the two booleans never disagree.
Which is why the DP is here to teach the pattern rather than to get this answer.
Stone Game II and Predict the Winner drop the guarantee, and there only the
recurrence is correct.

Complexity

  • Time — O(n^2) — one entry per subarray.
  • Space — O(n^2) for the table, reducible to O(n) with a rolling 1-D array.

Common Pitfalls

  • Do not store two scores per state. The margin formulation is what makes the recurrence a single max.
  • Forgetting the sign flip is the classic bug: piles[i] + dp[i+1][j] models a cooperative game, not an adversarial one — the margin for [5,3,4,5] becomes 17, which is just the sum of all piles. Be clear that no valid test can catch it here, though: with an even pile count and an odd total the first player always wins, so the shipped answer and the plus version are both true on every legal input. The recurrence is here to teach the pattern, not to get this answer.
  • The always-true shortcut relies on the pile count being even. Drop that guarantee and only the DP is correct — which is exactly what Stone Game II and Predict the Winner probe.

Full Solution — all languages

class Solution:
    def stoneGame(self, nums):
        n = len(nums)
        dp = nums[:]
        for length in range(2, n + 1):
            for i in range(n - length + 1):
                j = i + length - 1
                dp[i] = max(nums[i] - dp[i + 1], nums[j] - dp[i])
        return dp[0] > 0
SensAI
Beta
Tap the mic to stop voice mode