Stone Game III

Stones are arranged in a row, and stoneValue[i] is the value of the i-th stone (values can be negative). Alice and Bob take turns, Alice first. On each turn a player takes 1, 2 or 3 stones from the front of the remaining row, adding their values to their score. The game ends when all stones are taken. Both play optimally. Return "Alice" if Alice ends with the higher score, "Bob" if Bob does, or "Tie" if the scores are equal.

30:00

Stone Game III
hard
Free written solution
Topics
Companies

Stones are arranged in a row, and stoneValue[i] is the value of the i-th stone (values can be negative). Alice and Bob take turns, Alice first. On each turn a player takes 1, 2 or 3 stones from the front of the remaining row, adding their values to their score. The game ends when all stones are taken. Both play optimally. Return "Alice" if Alice ends with the higher score, "Bob" if Bob does, or "Tie" if the scores are equal.

Example 1:
Input: {"stoneValue":[1,2,3,7]}
Output: Bob
Constraints:
  • 1≤stoneValue.length≤5×1041 \leq \text{stoneValue.length} \leq 5 \times 10^4

  • −1000≤stoneValue[i]≤1000-1000 \leq \text{stoneValue}[i] \leq 1000

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"stoneValue":[1,2,3,7]}

dp[i] = how far ahead the player to move ends up when only stones i..3 are left. With no stones left the lead is 0, so dp[4] = 0. Fill dp from the back.

Row of stones (top) and dp[i] = lead of the player to move from i (bottom)

1

2

3

7

end

0

1

2

3

4

?
?
?
?
0
Variables
VariableValue
n4
dp[4]0
DepthFunction Call
Stack empty
0/16