AAlgoLoopSpaced repetition for LeetCode
MEDIUMDynamic ProgrammingLeetCode ↗

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

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

410310
Step-by-step visualization
Start free →

More Dynamic Programming problems