Stone Game
Difficulty: Medium · Pattern: 1-D Dynamic Programming · LeetCode #877
An even number of piles is in a row, and the total number of stones is odd (so there are no ties). Alice and Bob alternate turns, Alice first, and each takes the whole pile at either end. Both play optimally. Return true if Alice wins.
Examples
[5,3,4,5] → true
[3,7,2,3] → trueHints
- Define
dp[i][j]= the best (my stones − opponent's stones) for the player to move on pilesi..j. - Math insight: color the piles alternately. The first player can always take all the even-indexed piles or all the odd-indexed ones, whichever set is larger.
Approach
Interval DP (the general method):
dp[i][i] = piles[i]
dp[i][j] = max(piles[i] - dp[i+1][j], piles[j] - dp[i][j-1])The player to move takes one end, and then the opponent faces the remaining interval, where the opponent's advantage counts against us. Alice wins iff dp[0][n−1] > 0. That's O(n²), using a rolling 1-D array.
Shortcut: with an even number of piles, the first player can force taking all even-index or all odd-index piles. Those sums differ because the total is odd, so Alice always wins and return True is correct. Interviewers want the DP, because it generalizes (Stone Game II, III, Predict the Winner) while the trick doesn't.
Complexity
Time: O(n²). Space: O(n).
Python solution
def stoneGame(piles):
n = len(piles)
dp = piles[:]
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] > 0JavaScript solution
function stoneGame(piles) {
const n = piles.length, dp = [...piles];
for (let len = 2; len <= n; len++) for (let i = 0; i + len - 1 < n; i++) {
const j = i + len - 1;
dp[i] = Math.max(piles[i] - dp[i + 1], piles[j] - dp[i]);
}
return dp[0] > 0;
}