SDE & MLE Prep

877. Stone Game

Problem

An even number of piles lie in a row and their total is odd. Alice and Bob alternate, Alice first, each taking a whole pile from either end of the row. Both play optimally; return true if Alice ends with more stones.

Example: [5,3,4,5] → true

General method — interval DP on the score difference: dp[i][j] = max(piles[i] − dp[i+1][j], piles[j] − dp[i][j−1]), Alice wins if dp[0][n−1] > 0. For this problem there's a trick: with an even number of piles Alice can always take all even-indexed or all odd-indexed piles (whichever sum is larger), and the total is odd so there are no ties — she always wins. Interviewers want the DP and then the insight.

Complexity: O(n²) for the DP (O(1) with the parity argument).

class Solution:
    def stoneGame(self, piles: List[int]) -> bool:
        n = len(piles)
        dp = piles[:]                               # dp[i] for intervals of length 1
        for length in range(2, n + 1):
            for i in range(n - length + 1):
                j = i + length - 1
                dp[i] = max(piles[i] - dp[i + 1], piles[j] - dp[i])
        return dp[0] > 0