Stone Game VIII - 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, while the number of stones is more than one, they will do the following:
- Choose an integer
x > 1, and remove the leftmostxstones 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
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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code