




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.
1public class Solution {
2    public boolean PredictTheWinner(int[] nums) {
3        int n = nums.length;
4        int[][] memo = new int[n][n];
5        for (int i = 0; i < n; i++) {
6            for (int j = 0; j < n; j++) {
7                memo[i][j] = Integer.MIN_VALUE;
8            }
9        }
10        return calculate(nums, 0, n - 1, memo) >= 0;
11    }
12
13    private int calculate(int[] nums, int i, int j, int[][] memo) {
14        if (i == j) return nums[i];
15        if (memo[i][j] != Integer.MIN_VALUE) 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] = Math.max(pickI, pickJ);
19        return memo[i][j];
20    }
21}The Java solution follows the same recursive logic as the Python solution. It defines a helper function calculate which utilizes the memoization technique to store previously calculated results to avoid redundant 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.