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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code