6-lines Java O(n) solution with explanation

  • 0

    up->1 means we expect current nums[i] to be greater than nums[i-1]
    up->-1 means the opposite
    up->0 initial condition, won't change unless nums[i]!=nums[i-1], so avoid dupliates
    0 - up : switch between up=1 and up=-1
    inside the for loop:
    first line set up the 'up' variable initially.
    second line will increase counter if current nums[i] meets our expectation

    public class Solution {
        public int wiggleMaxLength(int[] nums) {
            int len = nums.length, up = 0, ct = 1;
            for(int i=1; i<len; i++){
                if(up == 0 && nums[i] != nums[i-1]) up = nums[i]>nums[i-1]?1:-1;
                if((up==1 && nums[i]>nums[i-1]) || (up==-1 && nums[i]<nums[i-1])) if(ct++ > 0) up = 0-up;
            return len==0?0:ct;

Log in to reply

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