1406. Stone Game III
Problem
Stones lie in a row with values stoneValue (possibly negative). Alice and Bob alternate, Alice first; each turn a player takes 1, 2 or 3 stones from the front of the row, adding their values to their score. Both play optimally. Return "Alice", "Bob" or "Tie" depending on who ends with the higher score.
Example: [1,2,3,7] → "Bob"; [1,2,3,-9] → "Alice"
Constraints: up to 5·10⁴ stones.
Zero-sum game → track the score difference for the player to move: dp[i] = max over k ∈ {1,2,3} of (sum of stones i..i+k−1) − dp[i+k]. Alice wins if dp[0] > 0, Bob if < 0, otherwise tie.
Complexity: O(n) time, O(1) extra space possible (only dp[i+1..i+3] needed).
class Solution:
def stoneGameIII(self, stoneValue: List[int]) -> str:
n = len(stoneValue)
dp = [0] * (n + 3)
for i in range(n - 1, -1, -1):
take, best = 0, float("-inf")
for k in range(3):
if i + k < n:
take += stoneValue[i + k]
best = max(best, take - dp[i + k + 1])
dp[i] = best
return "Alice" if dp[0] > 0 else "Bob" if dp[0] < 0 else "Tie"
assert Solution().stoneGameIII([1, 2, 3, 7]) == "Bob"
assert Solution().stoneGameIII([1, 2, 3, -9]) == "Alice"
assert Solution().stoneGameIII([1, 2, 3, 6]) == "Tie"
assert Solution().stoneGameIII([-1, -2, -3]) == "Tie"
class Solution {
public String stoneGameIII(int[] stoneValue) {
int n = stoneValue.length;
int[] dp = new int[n + 3];
for (int i = n - 1; i >= 0; i--) {
int take = 0, best = Integer.MIN_VALUE;
for (int k = 0; k < 3 && i + k < n; k++) {
take += stoneValue[i + k];
best = Math.max(best, take - dp[i + k + 1]);
}
dp[i] = best;
}
return dp[0] > 0 ? "Alice" : dp[0] < 0 ? "Bob" : "Tie";
}
}
func stoneGameIII(stoneValue []int) string {
n := len(stoneValue)
dp := make([]int, n+1) // dp[i] = best (mine - theirs) when it is my turn at i
for i := n - 1; i >= 0; i-- {
take, best := 0, math.MinInt
for k := 0; k < 3 && i+k < n; k++ {
take += stoneValue[i+k]
best = max(best, take-dp[i+k+1])
}
dp[i] = best
}
switch {
case dp[0] > 0:
return "Alice"
case dp[0] < 0:
return "Bob"
}
return "Tie"
}