C 1 line recursive solution


  • 2
    H
    bool helper(int* nums, int numsSize, int point, bool round){
        return !numsSize ? 
        point>0 || round && !point :
        !helper(nums+1, numsSize-1, -(point + nums[0]), !round) || !helper(nums, numsSize-1, -(point + nums[numsSize-1]), !round);
    }
    
    bool PredictTheWinner(int* nums, int numsSize) {
        return helper(nums, numsSize, 0, true);
    }
    

  • 0
    V

    It doesn't seem to follow the required strategy "each player plays to maximize his score", as the second part of the || statement doesn't evaluate if the first part evaluates as true, so the strategy is actually "each player plays to get more score than his opponent (and prefers to take the head of the remaining scores)". The strategy mentioned in the problem description is actually unnecessary and misleading.

    A slightly more readable version:

    bool PredictTheWinner(int* nums, int numsSize)
    {
        return canWin(nums, numsSize, 0, true);
    }
    
    int canWin(int* nums, int size, int score, bool isplayer1)
    {
        if (size == 0)
            return (isplayer1) ? score >= 0 : score > 0;
        else
            return !canWin(nums + 1, size - 1, -(score + nums[0]), !isplayer1) || !canWin(nums, size - 1, -(score + nums[size - 1]), !isplayer1);
    }
    

  • 0
    V
    This post is deleted!

  • 0
    J
    This post is deleted!

Log in to reply
 

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