O(n) solution in C


  • 0
    R
    int wiggleMaxLength(int* nums, int numsSize) {
        bool nextHigher;
        int diff, i, len ;
        if (numsSize <=1) {
            return numsSize;
        }
        
        len=1;
        i=1;
        while (i<numsSize) {
            if (nums[i] != nums[i-1]) {
                len=2;
                break;
            }
            i++;
        }
        
        nextHigher = nums[i] < nums[i-1];
        for (i=i+1; i<numsSize; i++) {
            diff = nums[i] - nums[i-1];
            if (nextHigher && diff > 0) {
                nextHigher = !nextHigher;
                len++;
            } else if (!nextHigher && diff < 0) {
                nextHigher = !nextHigher;
                len++;
            }
        }
        return len;
    }
    

Log in to reply
 

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