SDE & MLE Prep

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"