/**
* Problem: LeetCode 486 - Predict the Winner
* Difficulty: Medium
* Language: Java
* Author: CodeByTushu
*/
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 = 2; len <= n; len++) {
for (int i = 0; i <= n - len; i++) {
int j = i + len - 1;
dp[i][j] = Math.max(nums[i] - dp[i + 1][j], nums[j] - dp[i][j - 1]);
}
}
return dp[0][n - 1] >= 0;
}
}
"""
Problem: LeetCode 486 - Predict the Winner
Difficulty: Medium
Language: Python
Author: CodeByTushu
"""
class Solution:
def predictTheWinner(self, nums: list[int]) -> bool:
n = len(nums)
# dp[i][j] stores the maximum score difference achievable from nums[i..j]
dp = [[0] * n for _ in range(n)]
for i in range(n):
dp[i][i] = nums[i]
for length in range(2, n + 1):
for i in range(n - length + 1):
j = i + length - 1
dp[i][j] = max(nums[i] - dp[i + 1][j], nums[j] - dp[i][j - 1])
return dp[0][n - 1] >= 0
/**
* Problem: LeetCode 486 - Predict the Winner
* Difficulty: Medium
* Language: C++
* Author: CodeByTushu
*/
#include <vector>
#include <algorithm>
/**
* Problem: LeetCode 486 - Predict the Winner
* Difficulty: Medium
* Language: C++
* Author: CodeByTushu
*/
class Solution {
public:
bool predictTheWinner(std::vector<int>& nums) {
int n = nums.size();
std::vector<std::vector<int>> dp(n, std::vector<int>(n, 0));
for (int i = 0; i < n; ++i) {
dp[i][i] = nums[i];
}
for (int len = 2; len <= n; ++len) {
for (int i = 0; i <= n - len; ++i) {
int j = i + len - 1;
dp[i][j] = std::max(nums[i] - dp[i + 1][j], nums[j] - dp[i][j - 1]);
}
}
return dp[0][n - 1] >= 0;
}
};
/**
* Problem: LeetCode 486 - Predict the Winner
* Difficulty: Medium
* Language: JavaScript
* Author: CodeByTushu
*/
var predictTheWinner = function(nums) {
const n = nums.length;
const dp = Array.from({ length: n }, () => new Int32Array(n));
for (let i = 0; i < n; i++) {
dp[i][i] = nums[i];
}
for (let len = 2; len <= n; len++) {
for (let i = 0; i <= n - len; i++) {
const j = i + len - 1;
dp[i][j] = Math.max(nums[i] - dp[i + 1][j], nums[j] - dp[i][j - 1]);
}
}
return dp[0][n - 1] >= 0;
};
TIME COMPLEXITY
O(N^2)
SPACE COMPLEXITY
O(N^2)
TOPICS
Array
Dynamic Programming
Game Theory
Math
Recursion