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
assert Solution().stoneGame([5, 3, 4, 5]) is True
assert Solution().stoneGame([3, 7, 2, 3]) is True
assert Solution().stoneGame([1, 100, 2, 4]) is True
class Solution {
public boolean stoneGame(int[] piles) {
int n = piles.length;
int[] dp = piles.clone();
for (int len = 2; len <= n; len++)
for (int i = 0; i + len <= n; i++) dp[i] = Math.max(piles[i] - dp[i + 1], piles[i + len - 1] - dp[i]);
return dp[0] > 0;
}
}
func stoneGame(piles []int) bool {
n := len(piles)
dp := append([]int(nil), piles...) // dp[i] = best (mine - theirs) on piles[i..i+length-1]
for length := 2; length <= n; length++ {
for i := 0; i+length <= n; i++ {
j := i + length - 1
dp[i] = max(piles[i]-dp[i+1], piles[j]-dp[i])
}
}
return dp[0] > 0
}