1406. Stone Game III - Explanation
Description
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] <= 1000
Topics
Prerequisites
Before attempting this problem, you should be comfortable with:
- Dynamic Programming (Memoization) - Storing optimal results for each position to avoid recomputation
- Game Theory / Minimax - Modeling optimal play where both players make the best possible moves
- Score Difference Tracking - Using relative advantage (current player's score minus opponent's score) to simplify two-player game logic
- Space Optimization - Reducing DP space from O(n) to O(1) using rolling arrays when only recent states are needed
1. Dynamic Programming (Top-Down) - I
Intuition
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.
Algorithm
- Define
dfs(i, alice)whereiis the current index andaliceindicates whose turn it is. - Base case: if
i >= n, return0. - If it's Alice's turn (
alice = 1), initialize result to negative infinity. For each choice of1,2, or3stones, add their values to a running score and maximizescore + dfs(j + 1, 0). - If it's Bob's turn (
alice = 0), initialize result to positive infinity. For each choice, subtract the stone values and minimizescore + dfs(j + 1, 1). - Memoize using a 2D cache
dp[n][2]. - The final result
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"Time & Space Complexity
- Time complexity:
- Space complexity:
2. Dynamic Programming (Top-Down) - II
Intuition
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.
Algorithm
- Define
dfs(i)to return the maximum advantage (current player's score minus opponent's score) starting from indexi. - Base case: if
i >= n, return0. - For each choice of taking
1,2, or3stones, accumulate their total value and computetotal - dfs(j + 1). Take the maximum across all choices. - Memoize results in a 1D cache of size
n. - The result
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"Time & Space Complexity
- Time complexity:
- Space complexity:
3. Dynamic Programming (Bottom-Up)
Intuition
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.
Algorithm
- Create a DP array
dp[n+1]initialized to negative infinity, withdp[n] = 0as the base case. - Iterate from
i = n-1down to0. - For each
i, try taking1,2, or3stones. Accumulate the total and computedp[i] = max(dp[i], total - dp[j + 1]). - The value
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"Time & Space Complexity
- Time complexity:
- Space complexity:
4. Dynamic Programming (Space Optimized)
Intuition
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.
Algorithm
- Create a small DP array
dp[4]initialized to0. - Iterate from
i = n-1down to0. - For each
i, setdp[i % 4] = negative infinity. Try taking1,2, or3stones, accumulating the total and computingdp[i % 4] = max(dp[i % 4], total - dp[(j + 1) % 4]). - The value
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"Time & Space Complexity
- Time complexity:
- Space complexity: extra space.
Common Pitfalls
Not Handling Negative Stone Values
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.
Returning the Wrong Output Type
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.
Incorrect Base Case Handling
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.
Forgetting Both Players Play Optimally
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.
Sign in to join the discussion