Stone Game III - Problem

Alice and Bob continue their games with piles of stones. There are several stones arranged in a row, and each stone has an associated value which is an integer given in the array stoneValue.

Alice and Bob take turns, with Alice starting first. On each player's turn, that player can take 1, 2, or 3 stones from the first remaining stones in the row.

The score of each player is the sum of the values of the stones taken. The score of each player is 0 initially.

The objective of the game is to end with the highest score, and the winner is the player with the highest score and there could be a tie. The game continues until all the stones have been taken.

Assume Alice and Bob play optimally.

Return "Alice" if Alice will win, "Bob" if Bob will win, or "Tie" if they will end the game with the same score.

Input & Output

Example 1 — Alice Wins
$ Input: stoneValue = [1,-3,7,-4]
Output: "Alice"
💡 Note: Alice takes 3 stones (1,-3,7) for score 5, Bob takes 1 stone (-4) for score -4. Alice wins 5 > -4.
Example 2 — Bob Wins
$ Input: stoneValue = [-1,-2,-3]
Output: "Bob"
💡 Note: All values negative. Alice takes 1 stone (-1), Bob takes 2 stones (-2,-3) = -5. Bob wins since -5 > -1.
Example 3 — Tie Game
$ Input: stoneValue = [1,2,-3]
Output: "Tie"
💡 Note: Alice takes 2 stones (1,2) = 3, Bob takes 1 stone (-3) = -3. Both have same total: 0.

Constraints

  • 1 ≤ stoneValue.length ≤ 5 × 104
  • -1000 ≤ stoneValue[i] ≤ 1000

Visualization

Tap to expand
Stone Game III: Optimal Two-Player Strategy1-37-4Stone Values: [1, -3, 7, -4]Alice takes 3 stones: 1 + (-3) + 7 = 5Bob takes 1 stone: -4Alice: 5Bob: -4Alice Wins: 5 > -4Output: "Alice"Both players play optimally to maximize their own score
Understanding the Visualization
1
Input
Array of stone values: [1,-3,7,-4]
2
Game Play
Players alternate, taking 1-3 stones from start
3
Optimal Strategy
Alice takes [1,-3,7]=5, Bob takes [-4]=-4
Key Takeaway
🎯 Key Insight: Use DP to calculate maximum score difference each player can achieve from any position
Asked in
Google 12 Amazon 8 Microsoft 6
28.4K 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