Short Java Solution O(N)


  • 0
    public int wiggleMaxLength(int[] nums) {
            if (nums.length <= 1){
                return nums.length;
            }
            int currLen = 2;
            int maxLen = 0;
            int lastDiff = nums[1] - nums[0];
            for (int i = 1; i < nums.length - 1; ++i){
                int nextDiff = nums[i+1] - nums[i];
                if (nextDiff * lastDiff < 0){
                    ++currLen;
                } 
                maxLen = (currLen > maxLen) ? currLen : maxLen;
                lastDiff = (nextDiff != 0) ? nextDiff : lastDiff;   
            }
            return (lastDiff == 0) ? 1 : maxLen; 
        }
    

Log in to reply
 

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