Stone Game
The key idea
Track the best score *difference* the current player can force on each subarray, not raw stone counts.
dp[i][j] = (my stones) - (opponent's stones) on piles[i..j]. Taking an end pile flips the roles, so it subtracts the opponent's best answer on the rest: dp[i][j] = max(piles[i] - dp[i+1][j], piles[j] - dp[i][j-1]). Alex wins exactly when dp[0][n-1] > 0.Problem
Alex and Lee play a game with piles of stones. There are an even number of piles arranged in a row, and each pile has a positive integer number of stones piles[i].
The total number of stones across all piles is odd, so there are no ties. Alex and Lee take turns, with Alex going first. Each turn, a player takes the entire pile from either the start or the end of the row. This continues until there are no more piles left.
Assuming both players play optimally, return true if and only if Alex wins the game.
Constraints
2 <= piles.length <= 500piles.lengthis even1 <= piles[i] <= 500- The sum of
piles[i]is odd
Examples
Input: piles = [5,3,4,5]
Output: true
Input: piles = [3,7,2,3]
Output: true
Complexity
Time: O(n^2) Space: O(n^2)
See the full solution
- ✓Full worked approach
- ✓Reference code in 5 languages
- ✓Problem-solving tips
- ✓Step-by-step animated visualization
More Dynamic Programming problems
- Best Time to Buy and Sell StockEASY
- Best Time to Buy and Sell Stock IIIHARD
- Best Time to Buy and Sell Stock IVHARD
- Best Time to Buy and Sell Stock with CooldownMEDIUM
- Best Time to Buy and Sell Stock with Transaction FeeMEDIUM
- Burst BalloonsHARD
- Climbing StairsEASY
- Coin ChangeMEDIUM
- Coin Change IIMEDIUM
- Combination Sum IVMEDIUM
- Counting BitsEASY
- Decode WaysMEDIUM