#486
Predict the Winner
MediumArrayMathDynamic ProgrammingRecursionGame TheoryDynamic ProgrammingGame Theory
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²)
In the optimal approach, we use dynamic programming to store results of subproblems, avoiding redundant calculations. This allows us to efficiently determine the maximum score difference Player 1 can achieve over Player 2.
⚙️
Algorithm
4 steps- 1Step 1: Create a DP table where dp[i][j] represents the maximum score difference Player 1 can achieve over Player 2 from nums[i] to nums[j].
- 2Step 2: Initialize the table for single elements, where dp[i][i] = nums[i].
- 3Step 3: Fill the table for subarrays of increasing lengths, calculating the score difference based on choices from either end.
- 4Step 4: Return true if dp[0][n-1] >= 0, indicating Player 1 can win.
solution.py12 lines
1# Full working Python code
2
3def predict_the_winner(nums):
4 n = len(nums)
5 dp = [[0] * n for _ in range(n)]
6 for i in range(n):
7 dp[i][i] = nums[i]
8 for length in range(2, n + 1):
9 for left in range(n - length + 1):
10 right = left + length - 1
11 dp[left][right] = max(nums[left] - dp[left + 1][right], nums[right] - dp[left][right - 1])
12 return dp[0][n - 1] >= 0ℹ
Complexity note: The time complexity is O(n²) due to filling the DP table, which requires iterating through all pairs of indices. The space complexity is also O(n²) because we store results for all subarrays in the DP table.
- 1Player 1 can win if they can ensure a non-negative score difference against Player 2.
- 2Optimal play means both players will always choose the option that maximizes their score difference.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.