Simple O(n) Java Solution


  • 0
    A
    public int wiggleMaxLength(int[] nums) {
        if (nums.length < 2) return nums.length;
        int ret = 1, prev = nums[0], diff = nums[0] - nums[1];
        for (int i=1; i<nums.length; i++) {
            if (((nums[i] - prev) * diff < 0) || (diff == 0 && nums[i] - prev != 0)) { 
                ret++;
                diff = nums[i] - prev;
                prev = nums[i];
            }
            else prev = nums[i];
        }
        return ret;
    }
    

    Check for alternating pattern by multiplying current difference with previous difference.
    If not alternating, it means the sequence is increasing/decreasing, so we just update the previous number at the end of the wiggle sequence.


Log in to reply
 

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