Predict the Winner (LeetCode 486): Solution and Explanation
Two players take turns removing a number from either end of nums and adding it to their score. Player 1 moves first, both play optimally, and you return true if player 1 finishes with at least as many points as player 2.
Intuition
Greedy fails. In [3, 9, 1, 2] taking the bigger end (3) hands the 9 to player 2; taking 2 instead forces player 2 to open up the 9 for player 1.
What remains after any sequence of moves is always a contiguous window nums[i..j]. That window, plus whose turn it is, is the whole game state.
Store the score difference instead of two scores. If dp[i][j] is how far ahead the player to move can finish on the window, the same table works for both players.
Taking nums[i] gains that number, and then the opponent becomes the player to move on nums[i+1..j] and gets ahead by dp[i+1][j]. So the move is worth nums[i] - dp[i+1][j]. The right end is the mirror image.
Approach: Interval DP on the score lead
- Create an
n x ntable and setdp[i][i] = nums[i]. - For window length 2 up to
n, for each startiwith endj = i + length - 1: - Set
dp[i][j] = max(nums[i] - dp[i+1][j], nums[j] - dp[i][j-1]). - Return
dp[0][n-1] >= 0.
Step-by-step example
nums = [1, 5, 233, 7]
- Diagonal:
dp = 1, 5, 233, 7for the single numbers. - Length 2:
[1,5]→ max(1 - 5, 5 - 1) = 4;[5,233]→ 228;[233,7]→ 226. - Length 3:
[1,5,233]→ max(1 - 228, 233 - 4) = 229;[5,233,7]→ max(5 - 226, 7 - 228) = -221. - Length 4:
[1,5,233,7]→ max(1 - (-221), 7 - 229) = 222. dp[0][3] = 222 >= 0, so returntrue: player 1 takes 1 and later gets 233.
Code: Python, Java, C++
1class Solution:
2 def predictTheWinner(self, nums: List[int]) -> bool:
3 n = len(nums)
4 dp = [[0] * n for _ in range(n)]
5 for i in range(n):
6 dp[i][i] = nums[i]
7 for length in range(2, n + 1):
8 for i in range(n - length + 1):
9 j = i + length - 1
10 dp[i][j] = max(nums[i] - dp[i + 1][j], nums[j] - dp[i][j - 1])
11 return dp[0][n - 1] >= 01class Solution {
2 public boolean predictTheWinner(int[] nums) {
3 int n = nums.length;
4 int[][] dp = new int[n][n];
5 for (int i = 0; i < n; i++) {
6 dp[i][i] = nums[i];
7 }
8 for (int len = 2; len <= n; len++) {
9 for (int i = 0; i + len - 1 < n; i++) {
10 int j = i + len - 1;
11 dp[i][j] = Math.max(nums[i] - dp[i + 1][j], nums[j] - dp[i][j - 1]);
12 }
13 }
14 return dp[0][n - 1] >= 0;
15 }
16}1class Solution {
2public:
3 bool predictTheWinner(vector<int>& nums) {
4 int n = nums.size();
5 vector<vector<int>> dp(n, vector<int>(n, 0));
6 for (int i = 0; i < n; i++) {
7 dp[i][i] = nums[i];
8 }
9 for (int len = 2; len <= n; len++) {
10 for (int i = 0; i + len - 1 < n; i++) {
11 int j = i + len - 1;
12 dp[i][j] = max(nums[i] - dp[i + 1][j], nums[j] - dp[i][j - 1]);
13 }
14 }
15 return dp[0][n - 1] >= 0;
16 }
17};Time and space complexity
O(n^2)
There are about n²/2 windows and each is filled in O(1).
O(n^2)
The table; it can be cut to O(n) with a single row because each length only needs the previous one.
Other approaches
Minimax recursion with memo (time O(n^2), space O(n^2))
f(i, j) returns the best lead on nums[i..j], computed as max(nums[i] - f(i+1, j), nums[j] - f(i, j-1)) with a memo table. Same recurrence, top-down.
Plain recursion (time O(2^n), space O(n))
Try both ends at every turn without memo. With n at most 20 this is about a million paths and still passes, but it does not scale.
Even-length shortcut (time O(1) for even n, space O(1))
When n is even, player 1 can always take all even-index or all odd-index numbers, so they never lose. This answers half the cases instantly, but odd lengths still need the DP.
Common mistakes
- Playing greedily by always taking the bigger end.
[3, 9, 1, 2]shows it can lose a game player 1 can win. - Returning
dp[0][n-1] > 0. A tie counts as a win for player 1, so the check is>= 0. - Tracking two scores and forgetting whose turn it is. The difference formulation removes that bookkeeping.
- Filling the table in the wrong order.
dp[i][j]needsdp[i+1][j]anddp[i][j-1], so go by increasing window length (orifrom high to low).
Frequently asked questions
Why does subtracting dp of the rest work?
After you take an end, the opponent moves on the smaller window and, playing optimally, finishes ahead by dp of that window counted from their side. Your lead on the full window is what you took minus that.
Does player 2 need a separate table?
No. dp is always from the view of whoever moves next on that window, so it already describes player 2 on the windows they face.
How is this related to Stone Game?
Stone Game is the same game with an even number of piles and an odd total, where player 1 always wins. Predict the Winner allows any length and ties, so you actually have to compute the DP.