Alice and Bob are playing a game 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.
Example 1:
Input: stoneValue = [2,4,3,1]
Output: "Alice"Explanation: In first move, Alice will pick the first three stones (2,4,3) and in the second move Bob will pick the last remaining stone (1). The final score of Alice is (2 + 4 + 3 = 9) which is greater than the Bob's score (1).
Example 2:
Input: stoneValue = [1,2,1,5]
Output: "Bob"Explanation: In first move, Alice will pick the first three stones (1,2,1) and in the second move Bob will pick the last remaining stone (5). The final score of Alice is (1 + 2 + 1 = 4) which is lesser than the Bob's score (5).
Example 3:
Input: stoneValue = [5,-3,3,5]
Output: "Tie"Explanation: In first move, Alice will pick the first three stones (5,-3,3) and in the second move Bob will pick the last remaining stone (5). The final score of Alice is (5 + -3 + 3 = 5) which is equal to the Bob's score (5).
Constraints:
1 <= stoneValue.length <= 50,000-1000 <= stoneValue[i] <= 1000Before attempting this problem, you should be comfortable with:
Alice and Bob take turns picking 1, 2, or 3 stones from the front. Both play optimally: Alice maximizes her score while Bob minimizes Alice's score. We track the score difference (Alice minus Bob) throughout the game. At each state, we know whose turn it is and the current position. Alice adds stone values to the running score, while Bob subtracts them. The final result tells us who wins based on whether the difference is positive, negative, or zero.
dfs(i, alice) where i is the current index and alice indicates whose turn it is.i >= n, return 0.alice = 1), initialize result to negative infinity. For each choice of 1, 2, or 3 stones, add their values to a running score and maximize score + dfs(j + 1, 0).alice = 0), initialize result to positive infinity. For each choice, subtract the stone values and minimize score + dfs(j + 1, 1).dp[n][2].dfs(0, 1) represents Alice's score minus Bob's score. Return "Alice" if positive, "Bob" if negative, "Tie" if zero.class Solution:
def stoneGameIII(self, stoneValue: List[int]) -> str:
n = len(stoneValue)
dp = [[None] * 2 for _ in range(n)]
def dfs(i, alice):
if i >= n:
return 0
if dp[i][alice] is not None:
return dp[i][alice]
res = float("-inf") if alice == 1 else float("inf")
score = 0
for j in range(i, min(i + 3, n)):
if alice == 1:
score += stoneValue[j]
res = max(res, score + dfs(j + 1, 0))
else:
score -= stoneValue[j]
res = min(res, score + dfs(j + 1, 1))
dp[i][alice] = res
return res
result = dfs(0, 1)
if result == 0:
return "Tie"
return "Alice" if result > 0 else "Bob"We can simplify the recursion by treating both players symmetrically. At any position, the current player wants to maximize their advantage over the opponent. Since the game is zero-sum, if the current player takes some stones with total value T, and the opponent then plays optimally getting result R, the current player's relative advantage is T - R. This formulation eliminates the need to track whose turn it is.
dfs(i) to return the maximum advantage (current player's score minus opponent's score) starting from index i.i >= n, return 0.1, 2, or 3 stones, accumulate their total value and compute total - dfs(j + 1). Take the maximum across all choices.n.dfs(0) represents Alice's advantage. Return "Alice" if positive, "Bob" if negative, "Tie" if zero.class Solution:
def stoneGameIII(self, stoneValue: List[int]) -> str:
n = len(stoneValue)
dp = {}
def dfs(i):
if i >= n:
return 0
if i in dp:
return dp[i]
res, total = float("-inf"), 0
for j in range(i, min(i + 3, n)):
total += stoneValue[j]
res = max(res, total - dfs(j + 1))
dp[i] = res
return res
result = dfs(0)
if result == 0:
return "Tie"
return "Alice" if result > 0 else "Bob"Converting the recursive solution to iterative form, we fill the DP table from right to left. Each position stores the maximum advantage the current player can achieve from that point onward. Since each state only depends on the next three states, we process positions in reverse order to ensure dependencies are resolved.
dp[n+1] initialized to negative infinity, with dp[n] = 0 as the base case.i = n-1 down to 0.i, try taking 1, 2, or 3 stones. Accumulate the total and compute dp[i] = max(dp[i], total - dp[j + 1]).dp[0] represents Alice's advantage when starting the game. Return "Alice" if positive, "Bob" if negative, "Tie" if zero.class Solution:
def stoneGameIII(self, stoneValue: List[int]) -> str:
n = len(stoneValue)
dp = [float("-inf")] * (n + 1)
dp[n] = 0
for i in range(n - 1, -1, -1):
total = 0
for j in range(i, min(i + 3, n)):
total += stoneValue[j]
dp[i] = max(dp[i], total - dp[j + 1])
result = dp[0]
if result == 0:
return "Tie"
return "Alice" if result > 0 else "Bob"Since each state only depends on the next three states (dp[i+1], dp[i+2], dp[i+3]), we can reduce space from O(n) to O(1) by using a rolling array of size 4. We use modulo arithmetic to cycle through the array indices as we process positions from right to left.
dp[4] initialized to 0.i = n-1 down to 0.i, set dp[i % 4] = negative infinity. Try taking 1, 2, or 3 stones, accumulating the total and computing dp[i % 4] = max(dp[i % 4], total - dp[(j + 1) % 4]).dp[0] represents Alice's advantage. Return "Alice" if positive, "Bob" if negative, "Tie" if zero.class Solution:
def stoneGameIII(self, stoneValue: List[int]) -> str:
n = len(stoneValue)
dp = [0] * 4
for i in range(n - 1, -1, -1):
total = 0
dp[i % 4] = float("-inf")
for j in range(i, min(i + 3, n)):
total += stoneValue[j]
dp[i % 4] = max(dp[i % 4], total - dp[(j + 1) % 4])
if dp[0] == 0:
return "Tie"
return "Alice" if dp[0] > 0 else "Bob"Unlike other stone game problems, this one allows negative values. Greedily taking the maximum stones does not work because sometimes it is better to take fewer stones to force the opponent into a bad position. Your DP must consider all choices (1, 2, or 3 stones) even when some have negative values.
The problem asks for a string ("Alice", "Bob", or "Tie"), not a boolean or numeric score. A common mistake is returning the score difference instead of comparing it to determine the winner. Always convert the final score comparison into the correct string result.
When the index reaches or exceeds the array length, the remaining score is zero. Initializing this incorrectly or not handling the edge case where fewer than 3 stones remain causes out-of-bounds errors or wrong results. Ensure your loop condition properly checks i + X <= n before accessing elements.
Assuming Bob plays suboptimally (e.g., always takes 1 stone) leads to incorrect results. The DP must model Bob as a rational player who also maximizes his own score. In the score-difference formulation, this is handled by subtracting the opponent's optimal result from the current player's gain.