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: "Tie"
💡 Note: All values are negative. Alice can take 1 stone (-1), Bob takes 2 stones (-2,-3) = -5, Alice wins -1 > -5. Or Alice takes 2 stones (-1,-2) = -3, Bob takes 1 stone (-3), resulting in tie -3 = -3. Alice optimally chooses the tie.
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 - Dynamic Programming INPUT stoneValue array: 1 i=0 -3 i=1 7 i=2 -4 i=3 Game Rules: • Alice starts first • Take 1, 2, or 3 stones • From first remaining • Both play optimally Alice First Bob Second ALGORITHM STEPS 1 Define DP State dp[i] = max score diff from i 2 Recurrence dp[i] = max(sum - dp[i+k]) 3 Iterate Backward From n-1 to 0 4 Check dp[0] Compare with 0 DP Table (score diff): i 0 1 2 3 dp[i] 5 0 3 -4 dp[0] = max of taking 1,2,3 stones: take 1: 1 - dp[1] = 1 - 0 = 1 take 2: -2 - dp[2] = -2 - 3 = -5 take 3: 5 - dp[3] = 5 - (-4) = 5 FINAL RESULT dp[0] = 5 (positive) Score Analysis: Alice Score: 8 vs Bob Score: 3 Alice Wins! 8 > 3 Output: "Alice" dp[0] > 0 --> Alice dp[0] = 0 --> Tie dp[0] < 0 --> Bob Key Insight: dp[i] represents the maximum score difference (current player - opponent) starting from index i. When player takes k stones, opponent plays optimally from i+k, so we subtract dp[i+k]. Final answer: dp[0] > 0 means Alice wins, dp[0] < 0 means Bob wins, dp[0] = 0 is a Tie. TutorialsPoint - Stone Game III | Dynamic Programming Approach Time: O(n) | Space: O(n)
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