Alice and Bob play a game with a row of stones, where the value of each stone is given in the array stones. Alice goes first and the players alternate turns. On a turn, a player removes either the leftmost or the rightmost remaining stone and earns points equal to the sum of the values of all stones that are still on the row after the removal.
Both players play optimally, and each one wants to maximize the difference between their own total score and the opponent's total score. Return the difference between Alice's score and Bob's score at the end of the game assuming both play optimally.
Example 1
Input: stones = [5,3,1,4,2]
Output: 6
With optimal play the players trim the row from both ends so that Alice keeps a lead of exactly 6 points over Bob by always choosing the end that maximizes her own margin.
Example 2
Input: stones = [7,90,5,1,100,10,10,2]
Output: 122
Each removal scores the sum of what remains, so early moves are worth the most. Optimal alternating choices leave Alice ahead by 122 points.
Constraints
n == stones.length2 <= n <= 10001 <= stones[i] <= 1000See the step-by-step animation, the intuition, and clean code in every language — free, no credit card.
FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.
750+ engineers trained · frontend, backend, AWS & AI