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, while the number of stones is more than one, they will do the following:

  • Choose an integer x > 1, and remove the leftmost x stones from the row.
  • Add the sum of the removed stones' values to the player's score.
  • Place a new stone, whose value is equal to that sum, on the left side of the row.

The game stops when only one stone is left in the row.

The score difference between Alice and Bob is (Alice's score - Bob's score). Alice's goal is to maximize the score difference, and Bob's goal is to minimize the score difference.

Given an integer array stones of length n where stones[i] represents the value of the ith stone from the left, return the score difference between Alice and Bob if they both play optimally.

Input & Output

Example 1 — Small Array
$ Input: stones = [-1,2,-3,4,-5]
Output: 5
💡 Note: Alice can take the first 4 stones (sum = -1+2+(-3)+4 = 2), then Bob must take the remaining stones [2,-5] (sum = -3), giving Alice advantage of 2-(-3) = 5.
Example 2 — All Positive
$ Input: stones = [7,-6,5,10,5,-2,-6]
Output: 13
💡 Note: Alice plays optimally to maximize score difference, achieving a final advantage of 13.
Example 3 — Minimum Size
$ Input: stones = [-10,20]
Output: 10
💡 Note: Alice must take both stones (sum = 10), Bob gets nothing, so difference is 10.

Constraints

  • 3 ≤ stones.length ≤ 104
  • -104 ≤ stones[i] ≤ 104

Visualization

Tap to expand
Stone Game VIII: Alice vs Bob StrategyInitial: [-1, 2, -3, 4, -5]-12-34-5Alice's TurnCan take 2,3,4, or 5 stonesAlice takes first 4: sum = 2After Alice: [2, -5]2-5Bob must take both: sum = -3Final Scores:Alice: 2Bob: -3Score Difference: 2 - (-3) = 5Alice maximizes advantage, Bob minimizes it - both play optimally
Understanding the Visualization
1
Game Setup
Alice and Bob alternate turns, Alice starts first
2
Move Rules
Take ≥2 leftmost stones, add sum to score, replace with single stone
3
Objective
Alice maximizes (her score - Bob's score), Bob minimizes it
Key Takeaway
🎯 Key Insight: This is a minimax problem where optimal play requires dynamic programming to evaluate all possible future game states
Asked in
Google 12 Amazon 8 Microsoft 6
28.5K Views
Medium Frequency
~35 min Avg. Time
892 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