Stone Game III
Hard
Topics
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
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
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
- Allocate
dpof lengthn+1withdp[n] = 0. - Sweep
ifromn-1down to 0. - Accumulate the taken sum over the one, two and three cases, scoring each as
taken - dp[i + take]. - Store the maximum.
- 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
bestto 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]import java.util.*;
class Solution {
public int stoneGameIII(int[] nums) {
int[] s = nums;
int n = s.length;
int[] dp = new int[n + 1];
for (int i = n - 1; i >= 0; i--) {
int take = 0, best = Integer.MIN_VALUE;
for (int x = 0; x < 3 && i + x < n; x++) {
take += s[i + x];
int val = take - dp[i + x + 1];
if (val > best) best = val;
}
dp[i] = best;
}
return dp[0];
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int stoneGameIII(vector<int>& nums) {
vector<int>& s = nums;
int n = s.size();
vector<int> dp(n + 1, 0);
for (int i = n - 1; i >= 0; i--) {
int take = 0, best = INT_MIN;
for (int x = 0; x < 3 && i + x < n; x++) {
take += s[i + x];
int val = take - dp[i + x + 1];
if (val > best) best = val;
}
dp[i] = best;
}
return dp[0];
}
};/**
* @param {number[]} nums
* @return {number}
*/ var stoneGameIII = function(nums) {
const s = nums, n = s.length;
const dp = new Array(n + 1).fill(0);
for (let i = n - 1; i >= 0; i--) {
let take = 0, best = -Infinity;
for (let x = 0; x < 3 && i + x < n; x++) {
take += s[i + x];
const val = take - dp[i + x + 1];
if (val > best) best = val;
}
dp[i] = best;
}
return dp[0];
};