In this Leetcode Predict the Winner problem solution You are given an integer array nums. Two players are playing a game with this array: player 1 and player 2.

Player 1 and player 2 take turns, with player 1 starting first. Both players start the game with a score of 0. At each turn, the player takes one of the numbers from either end of the array (i.e., nums[0] or nums[nums.length - 1]) which reduces the size of the array by 1. The player adds the chosen number to their score. The game ends when there are no more elements in the array.

Return true if Player 1 can win the game. If the scores of both players are equal, then player 1 is still the winner, and you should also return true. You may assume that both players are playing optimally.

Leetcode Predict the Winner problem solution


Problem solution in Python.

from functools import lru_cache
from typing import List

class Solution:
    def PredictTheWinner(self, nums: List[int]) -> bool:
        if not nums:
            return None
        
        @lru_cache(maxsize=None)
        def bestScoreAdvantage(lo, hi):
            if lo > hi:
                return 0
            
            # Return the best score advantage you can get from:
            # - Playing one valid move
            # - Plug the negation of the best score advantage of the opponent
            return max(
                nums[lo] - bestScoreAdvantage(lo+1, hi),
                nums[hi] - bestScoreAdvantage(lo, hi-1)
            )
            
        return bestScoreAdvantage(0, len(nums)-1) >= 0

Problem solution in Java.

class Solution {
    public boolean PredictTheWinner(int[] nums) {
        int sum = 0;
        for(int i : nums)
            sum+=i;
        int[][] dp = new int[nums.length][nums.length];
        for(int[] d : dp)
            Arrays.fill(d, -1);
        return (sum+1)/2<=getAns(0, nums.length-1, dp,nums);
    }
    
    public int getAns(int i , int j, int[][] dp, int[] nums){
        if(i>j)
            return 0;
        if(dp[i][j] != -1)
            return dp[i][j];
        return dp[i][j] = Math.max(
        Math.min(nums[i]+getAns( i+1,j-1, dp, nums),nums[i]+getAns( i+2,j, dp, nums)),
        Math.min(nums[j]+getAns( i+1,j-1, dp, nums),nums[j]+getAns( i,j-2, dp, nums))
        );
    }
}


Problem solution in C++.

class Solution {
public:
    bool PredictTheWinner(vector<int>& nums) {
        if (nums.size()<3) return true;
        return helper(0, nums.size()-1, 1, 0, nums);
    }
    bool helper(int left, int right, int turn, int val, vector<int>& nums){
        if (left==right) return (turn*nums[left]+val)>=0;
        if (turn==1) {
            return helper(left+1, right, -turn, val+turn*nums[left], nums)||helper(left, right-1, -turn, val+turn*nums[right],nums);
        }
        else{
           return helper(left+1, right, -turn, val+turn*nums[left], nums) && helper(left, right-1, -turn, val+turn*nums[right], nums); 
        }
    }
};