Stone Game VII - Problem

Alice and Bob take turns playing a game, with Alice starting first.

There are n stones arranged in a row. On each player's turn, they can remove either the leftmost stone or the rightmost stone from the row and receive points equal to the sum of the remaining stones' values in the row.

The winner is the one with the higher score when there are no stones left to remove.

Bob found that he will always lose this game (poor Bob, he always loses), so he decided to minimize the score's difference. Alice's goal is to maximize the difference in the score.

Given an array of integers stones where stones[i] represents the value of the ith stone from the left, return the difference in Alice and Bob's score if they both play optimally.

Input & Output

Example 1 — Basic Game
$ Input: stones = [5,3,1,4,2]
Output: 6
💡 Note: Alice starts and plays optimally. One optimal sequence: Alice removes 2 (scores 5+3+1+4=13), Bob removes 5 (scores 3+1+4=8), Alice removes 4 (scores 3+1=4), Bob removes 1 (scores 3), Alice takes 3 (scores 0). Alice: 13+4=17, Bob: 8+3=11. Difference: 17-11=6.
Example 2 — Small Array
$ Input: stones = [7,90,5,1,100,10,10,2]
Output: 122
💡 Note: With optimal play from both players, Alice can achieve a score difference of 122 points.
Example 3 — Minimum Size
$ Input: stones = [3,7]
Output: 4
💡 Note: Alice can remove 3 (gets score 7) or remove 7 (gets score 3). She chooses to remove 3, then Bob must take 7 (gets score 0). Alice: 7, Bob: 0. Difference: 7-0=7. Wait, let me recalculate: if Alice removes 3, remaining is [7], Bob gets 0 points. If Alice removes 7, remaining is [3], Bob gets 0 points. Alice gets 7 or 3 respectively. So Alice gets max(7,3)=7, difference is 7.

Constraints

  • n == stones.length
  • 2 ≤ n ≤ 1000
  • 1 ≤ stones[i] ≤ 1000

Visualization

Tap to expand
Stone Game VII: Alice vs BobPlayers alternate removing stones from ends, score = sum of remaining stones53142Alice canremove 5Alice canremove 2Example Move: Alice removes 2Remaining stones: [5,3,1,4]Alice scores: 5+3+1+4 = 13 pointsWith optimal play: Alice advantage = 6
Understanding the Visualization
1
Input
Array of stone values [5,3,1,4,2]
2
Game Play
Players alternate removing leftmost or rightmost stones
3
Scoring
Score equals sum of remaining stones after removal
4
Output
Maximum score difference Alice can achieve: 6
Key Takeaway
🎯 Key Insight: Each player must consider opponent's optimal response when choosing their move
Asked in
Google 12 Amazon 8 Facebook 6
23.4K Views
Medium Frequency
~25 min Avg. Time
847 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen