376. Wiggle Subsequence

class Solution {
    public int wiggleMaxLength(int[] nums) {
        // caches the size of the largest wiggle subsequence
        int[] memo= new int[nums.length];
        // caches if the last diff at index is positive or negative;
        int[] sign = new int[nums.length];
        int ans = 0;
        for (int i=0; i<nums.length; i++){
            memo[i]=1;
            for (int j=0; j<i; j++){
              if(memo[j]==1 && memo[j]+1>memo[i] && nums[i]!=nums[j]){
                  memo[i]=2;
                  sign[i]= nums[i]>nums[j]? 1 : -1;
              }else if (memo[j]>1 && (nums[i]-nums[j])*sign[j]<0 && memo[j]+1 >memo[i]){
                  memo[i]=memo[j]+1;
                  sign[i] = nums[i]>nums[j]? 1 : -1;
              }
            }
            ans=Math.max(ans, memo[i]);
        }
        return ans;
    }
}

Last updated

Was this helpful?