Stone Game V - Problem

There are several stones arranged in a row, and each stone has an associated value which is an integer given in the array stoneValue.

In each round of the game, Alice divides the row into two non-empty rows (i.e. left row and right row), then Bob calculates the value of each row which is the sum of the values of all the stones in this row. Bob throws away the row which has the maximum value, and Alice's score increases by the value of the remaining row. If the value of the two rows are equal, Bob lets Alice decide which row will be thrown away.

The next round starts with the remaining row.

The game ends when there is only one stone remaining. Alice's score is initially zero.

Return the maximum score that Alice can obtain.

Input & Output

Example 1 — Basic Game
$ Input: stoneValue = [6,2,3,4,5,5]
Output: 18
💡 Note: Alice can split at index 2: left=[6,2,3]=11, right=[4,5,5]=14. Bob takes 14, Alice gets 11. Continue with [6,2,3] to get total score 18.
Example 2 — Small Array
$ Input: stoneValue = [7,7,7,7,7,7,7]
Output: 28
💡 Note: All stones have equal value. Alice can make strategic splits to maximize her remaining portions, achieving a total score of 28.
Example 3 — Minimum Size
$ Input: stoneValue = [4]
Output: 0
💡 Note: Only one stone remaining, game ends immediately. Alice's score is 0.

Constraints

  • 1 ≤ stoneValue.length ≤ 500
  • 1 ≤ stoneValue[i] ≤ 106

Visualization

Tap to expand
Stone Game V - Greedy Approach INPUT stoneValue array: 6 2 3 4 5 5 0 1 2 3 4 5 Total Sum = 25 Game Rules: 1. Alice splits row into 2 parts 2. Bob finds sum of each part 3. Bob throws away MAX row 4. Alice scores = MIN row value 5. Repeat until 1 stone left stoneValue = [6, 2, 3, 4, 5, 5] ALGORITHM STEPS 1 Split [6,2,3,4,5,5] Left:[6,2,3]=11 Right:[4,5,5]=14 Bob throws [4,5,5], Alice +11 2 Split [6,2,3] Left:[6]=6 Right:[2,3]=5 Bob throws [6], Alice +5 3 Split [2,3] Left:[2]=2 Right:[3]=3 Bob throws [3], Alice +2 4 Game Ends Only [2] remains - STOP Score Accumulation: Round 1: 0 + 11 = 11 Round 2: 11 + 5 = 16 Round 3: 16 + 2 = 18 FINAL RESULT Optimal Split Path: [6,2,3,4,5,5] [6,2,3] +11 [2,3] +5 [2] +2 Maximum Score: 18 OK - Verified Key Insight: The greedy approach tries all possible splits at each step and picks the one that maximizes Alice's total score. Alice always keeps the smaller sum (since Bob throws away the larger one), so she strategically splits to maximize the sum of all smaller portions across all rounds. Dynamic programming with memoization optimizes this. TutorialsPoint - Stone Game V | Greedy Approach
Asked in
Google 15 Facebook 12 Amazon 8
28.0K 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