




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
This Java solution constructs a 2D DP table where dp[i][j] represents the maximum advantageous score a player can ensure from the subarray nums[i...j]. Filling starts from single elements and progresses to larger subarrays, comparing feasible moves.