#1406
Stone Game III
HardArrayMathDynamic ProgrammingGame TheoryDynamic ProgrammingMinimax Strategy
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution uses dynamic programming to store the maximum score difference Alice can achieve from each index. This avoids redundant calculations and allows us to build the solution efficiently.
⚙️
Algorithm
3 steps- 1Step 1: Create a DP array where dp[i] represents the maximum score difference Alice can achieve starting from index i.
- 2Step 2: Iterate backwards through the stoneValue array, calculating the maximum score Alice can achieve for taking 1, 2, or 3 stones.
- 3Step 3: Use the DP values to determine the final result based on the score difference.
solution.py16 lines
1def stoneGameIII(stoneValue):
2 n = len(stoneValue)
3 dp = [float('-inf')] * (n + 1)
4 dp[n] = 0
5 for i in range(n - 1, -1, -1):
6 total = 0
7 for x in range(1, 4):
8 if i + x <= n:
9 total += stoneValue[i + x - 1]
10 dp[i] = max(dp[i], total - dp[i + x])
11 if dp[0] > 0:
12 return 'Alice'
13 elif dp[0] < 0:
14 return 'Bob'
15 else:
16 return 'Tie'ℹ
Complexity note: The time complexity is O(n) because we iterate through the stoneValue array once, and for each index, we perform a constant amount of work (up to 3 moves). The space complexity is O(n) due to the DP array.
- 1Alice and Bob both play optimally, meaning they will always make the best possible move to maximize their score.
- 2The game can be viewed as a minimax problem where one player's gain is the other's loss.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.