




Sponsored
Sponsored
This approach involves using recursion to explore all possible decisions by each player. With each choice, the players reduce the size of the array by selecting an element from either the start or end. Memoization is used to store intermediate results to minimize computational overhead by avoiding repeated calculations.
Time Complexity: O(n²) - Each state (i, j) is computed once.
Space Complexity: O(n²) - Intermediate results are stored in the memoization table.
1#include <vector>
2#include <algorithm>
3
4class Solution {
5public:
6    bool PredictTheWinner(std::vector<int>& nums) {
7        int n = nums.size();
8        std::vector<std::vector<int>> memo(n, std::vector<int>(n, INT_MIN));
9        return calculate(nums, 0, n - 1, memo) >= 0;
10    }
11
12private:
13    int calculate(std::vector<int>& nums, int i, int j, std::vector<std::vector<int>>& memo) {
14        if (i == j) return nums[i];
15        if (memo[i][j] != INT_MIN) return memo[i][j];
16        int pickI = nums[i] - calculate(nums, i + 1, j, memo);
17        int pickJ = nums[j] - calculate(nums, i, j - 1, memo);
18        memo[i][j] = std::max(pickI, pickJ);
19        return memo[i][j];
20    }
21};The C++ solution is similar to the Java and Python solutions. It uses the helper function calculate which recursively determines the optimal score a player can secure, storing results in a memo matrix to avoid repeated calculations.
This approach utilizes dynamic programming to solve the problem iteratively. Instead of recursion, it fills up a DP table where each entry represents the best possible score difference a player can achieve for a subarray defined by its boundaries.
Time Complexity: O(n²) - The table is filled once for every distinct range.
Space Complexity: O(n²) - The DP table consumes space proportional to n².
1    public bool 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;
    }
}The C# solution constructs a DP table dp where each element dp[i, j] holds the maximum score difference achievable starting with subarray nums[i...j], determined using a bottom-up approach.