Stone Game III

Hard

Topics
ArrayMathDynamic ProgrammingGame Theory

Given nums (the value of each stone in a row), Alice and Bob alternate turns with Alice first. On a turn a player takes the first 1, 2, or 3 remaining stones. Both play optimally to maximize their own total. Return Alice's score minus Bob's score (positive if Alice wins, negative if Bob wins, 0 for a tie).

Example 1

10213273
Input:  nums = [1,2,3,7]
Output: -1
Explanation: Alice takes 1+2+3=6, Bob gets 7, so 6-7=-1. Taking fewer stones is worse: 1+2 leaves Bob 3+7=10 for -7, and 1 alone leaves Bob 2+3+7=12 for -11.

Example 2

10213263
Input:  nums = [1,2,3,6]
Output: 0

Constraints

  • 1 <= nums.length <= 5*10^4
  • -1000 <= nums[i] <= 1000
Editorial — intuition, approach, complexity and pitfalls

Intuition

The move set is fixed and small — take one, two or three from the front — so the state is just the index. dp[i] is the best achievable (my score minus the opponent's) from nums[i:] onward, with the same sign-flip device as the other game problems: whatever the current player takes, the opponent then achieves dp[i+take] for themselves, so the net is sum(taken) - dp[i+take].

That makes it a plain one-dimensional suffix DP with three transitions per state, so O(n) overall. The running sum inside the inner loop avoids recomputing the taken total.

The answer's sign is the verdict: positive means Alice wins, negative means Bob, zero is a tie. Returning the difference rather than a verdict string is what this page's statement asks for.

Approach

  1. Allocate dp of length n+1 with dp[n] = 0.
  2. Sweep i from n-1 down to 0.
  3. Accumulate the taken sum over the one, two and three cases, scoring each as taken - dp[i + take].
  4. Store the maximum.
  5. Return dp[0].

Dry Run

values = [1,2,3,7]

  i=3  take 1 (sum 7)  - dp[4]=0  ->  7                      dp[3] = 7
  i=2  take 1 (sum 3)  - dp[3]=7  -> -4
       take 2 (sum 10) - dp[4]=0  -> 10                      dp[2] = 10
  i=1  take 1 (sum 2)  - dp[2]=10 -> -8
       take 2 (sum 5)  - dp[3]=7  -> -2
       take 3 (sum 12) - dp[4]=0  -> 12                      dp[1] = 12
  i=0  take 1 (sum 1)  - dp[1]=12 -> -11
       take 2 (sum 3)  - dp[2]=10 -> -7
       take 3 (sum 6)  - dp[3]=7  -> -1                      dp[0] = -1

answer -1, so Bob wins

every first move is bad for Alice: taking 1, 2 or 3 all leave Bob the 7.

Complexity

  • Time — O(n): three transitions per index.
  • Space — O(n) for the table, reducible to O(1) by keeping only the next three values — worth offering, since the recurrence never looks further than three ahead.

Common Pitfalls

  • Initialising best to 0 instead of negative infinity. Values can be negative, so a forced bad move must be allowed to produce a negative result.
  • Forgetting the bounds check on i + x < n, which reads past the end near the tail.
  • Resetting the running taken sum inside the inner loop, which recomputes from scratch and loses the accumulation that makes the three cases cheap.
  • Writing taken + dp[i+take]. The sign flip is the turn change; adding models cooperation.
  • Returning a boolean. This statement asks for the signed difference, and collapsing it to a winner throws away the tie distinction.
  • Being tempted by greedy. On [1,2,3,7] every greedy rule picks a losing first move, which is exactly why the DP exists.

Full Solution — all languages

class Solution:
    def stoneGameIII(self, nums):
        s = nums
        n = len(s)
        dp = [0] * (n + 1)
        for i in range(n - 1, -1, -1):
            take = 0
            best = float('-inf')
            for x in range(3):
                if i + x < n:
                    take += s[i + x]
                    val = take - dp[i + x + 1]
                    if val > best:
                        best = val
            dp[i] = best
        return dp[0]
SensAI
Beta
Tap the mic to stop voice mode