Short Java solution (with explanation)


  • 0
    O

    Explanation:
    When player 1 makes a move he can select either first or last number and either can give him the win.
    When player 2 makes a move, he also tries to win, so the only way player 1 can win - when both player 2 choises lead to player 1 win.

    public class Solution {
        public boolean PredictTheWinner(int[] nums) {
            return isPlayer1Winning(1, 0, 0, nums, 0, nums.length - 1);
        }
        
        private boolean isPlayer1Winning(int player, int p1Score, int p2Score, int[] nums, int start, int end) {
            if (start > end) {
                return p1Score >= p2Score;
            } else {
                if (player == 1) {
                    return isPlayer1Winning(2, p1Score + nums[start], p2Score, nums, start + 1, end)
                           || isPlayer1Winning(2, p1Score + nums[end], p2Score, nums, start, end - 1);
                } else {
                    return isPlayer1Winning(1, p1Score, p2Score + nums[start], nums, start + 1, end)
                           && isPlayer1Winning(1, p1Score, p2Score + nums[end], nums, start, end - 1);
                }
            }
        }
    }
    

Log in to reply
 

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