SDE & MLE Prep

1140. Stone Game II

Problem

Piles lie in a row; Alice and Bob alternate, Alice first, starting with M = 1. A player takes all stones from the first X remaining piles, with 1 ≤ X ≤ 2M, and then M becomes max(M, X). Both play optimally; return the most stones Alice can get.

Example: [2,7,9,4,4] → 10; [1,2,3,4,5,100] → 104

Constraints: up to 100 piles.

State (i, M): the player to move can take the next x ∈ [1, 2M] piles. With suffix sums, the stones this player ends with = suffix[i] − (what the opponent gets from (i + x, max(M, x))); maximize over x. If i + 2M ≥ n, take everything.

Complexity: O(n³) time, O(n²) states.

class Solution:
    def stoneGameII(self, piles: List[int]) -> int:
        n = len(piles)
        suffix = list(itertools.accumulate(reversed(piles)))[::-1] + [0]

        @cache
        def best(i, m):
            if i + 2 * m >= n:
                return suffix[i]
            return max(suffix[i] - best(i + x, max(m, x)) for x in range(1, 2 * m + 1))

        return best(0, 1)