Java - Concise Recursive


  • 0

    Note 1: Player 1 and Play 2 change roles after each round.
    Note 2: You also can get ideas from https://leetcode.com/problems/can-i-win/

    public class Solution {
        public boolean PredictTheWinner(int[] nums) {
            return canWin(nums, 0, nums.length - 1, 0, 0, true); 
        }
        public boolean canWin (int[] nums, int lo, int hi, int pt1, int pt2, boolean player1) {
            // Player 1 wins by collecting more points than Player 2 in the end, or they are tied in points. 
            if (lo == hi) return (pt1 + nums[lo] > pt2) || (pt1 + nums[lo] == pt2 && player1) ? true : false; 
            if(!canWin(nums, lo + 1, hi, pt2, pt1 + nums[lo], !player1) 
                || !canWin(nums, lo, hi - 1, pt2, pt1 + nums[hi], !player1)) return true; 
    
            return false; 
        }
    }

Log in to reply
 

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