Easy Java O(n) Solution


  • 0
    U

    Solution

    public int wiggleMaxLength(int[] nums) {
            if(nums.length<=1)
                return nums.length;
            if(nums[1]==0 && nums[0]==0) return 1;
            int len=2;
            
            int pre=nums[1]-nums[0];
            for(int i=2;i<nums.length;i++) {
                int cur=nums[i]-nums[i-1];
                if((cur>0 && pre<0) || (cur<0 && pre>0)) {
                    len++;
                    pre=cur;
                }
            }
            return len;
        }

Log in to reply
 

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