LeetCode 486: Predict the Winner Solution
Master LeetCode problem 486 (Predict the Winner), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
486. Predict the Winner
Problem Explanation
Explanation:
To solve this problem, we can use dynamic programming. We can create a 2D dp array where dp[i][j] represents the maximum score player 1 can get from nums[i:j+1]. The base cases are when i==j, dp[i][i] = nums[i] and when i > j, dp[i][j] = 0.
The dynamic programming approach involves filling up the dp array diagonally. We iterate over the array in a way that we first fill up for all subsequences of length 1, then length 2, and so on up to the length of the full array.
At each step, we consider two options: either player 1 picks nums[i] or nums[j]. If player 1 picks nums[i], then player 2 will play optimally and player 1 will get the remaining score from dp[i+1][j]. Similarly, if player 1 picks nums[j], then player 2 will play optimally and player 1 will get the remaining score from dp[i][j-1].
Finally, we check if the score player 1 can get by following the above strategy is greater than or equal to half of the total sum of the array. If it is, then player 1 can win the game.
Time Complexity: O(n^2) Space Complexity: O(n^2)
:
Solution Code
class Solution {
public boolean PredictTheWinner(int[] nums) {
int n = nums.length;
int[][] dp = new int[n][n];
for (int i = 0; i < n; i++) {
dp[i][i] = nums[i];
}
for (int len = 1; len < n; len++) {
for (int i = 0; i < n - len; i++) {
int j = i + len;
dp[i][j] = Math.max(nums[i] - dp[i + 1][j], nums[j] - dp[i][j - 1]);
}
}
return dp[0][n - 1] >= 0;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 486 (Predict the Winner)?
This page provides optimized solutions for LeetCode problem 486 (Predict the Winner) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 486 (Predict the Winner)?
The time complexity for LeetCode 486 (Predict the Winner) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 486 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 486 in Java, C++, or Python.