Potential wrong answer?


  • 0
    A

    Here is what i tried

    public class Solution {
        
        public boolean PredictTheWinner(int[] nums) {
            
            if(nums.length==1)
                return true;
        
            int left=0;
            int right=nums.length-1;
            boolean p1Turn = true;
            
            return play(left,right,nums,p1Turn,0,0);
        }
        
        boolean play(int left, int right, int [] nums, boolean p1Turn,int p1Score, int p2Score)
        {
            System.out.println("Incoming "+"P1:"+p1Score+" P2:"+p2Score);
            if(left==right-1)
            {
                if(p1Turn)
                {    
                    p1Score += Math.max(nums[left],nums[right]);
                    p2Score += Math.min(nums[left],nums[right]);
                }
                else
                {   
                    p2Score += Math.max(nums[left],nums[right]);
                    p1Score += Math.min(nums[left],nums[right]);
                }
                System.out.println("Left:"+nums[left]+",Right:"+nums[right]+"<---->"+"P1:"+p1Score+" P2:"+p2Score);
                return p1Score>=p2Score ? true : false;
            }
            
            if(p1Turn)
            {    
                return play(left+1,right,nums,false,p1Score+nums[left],p2Score) || play(left,right-1,nums,false,p1Score+nums[right],p2Score);
            }
            else
            {
                return play(left+1,right,nums,true,p1Score,p2Score+nums[left]) || play(left,right-1,nums,true,p1Score,p2Score+nums[right]);
            }
        }
    }
    

    Can some please explain what am i doing wrong? Especially for the input
    [2,4,55,6,8]

    I think the result should be true but the expected answer is false. Here is a path to player1's victory

    1. P1 picks 2
    2. P2 picks 4
    3. P1 picks 55
    4. P2 picks 6
    5. P1 picks 8

    P1's total is 65 and P2's total is 10, so clearly P1 wins. Why is false the expected answer


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.