Easy to understand Java solution


  • 0
    R

    Update the array to record the difference, count the numbers of elements not equal to 0. Count the contiguous positive/negative elements as 1.

    public int wiggleMaxLength(int[] nums) {
            if(nums == null || nums.length == 0){
                return 0;
            }
            int len = nums.length;
            if(len == 1){
                return 1;
            }
            for(int i = 0; i < len-1; i++){
                nums[i] = nums[i+1]-nums[i];
            }
            int max = 0;
            int prev = 0;
            for(int i = 0; i < len-1; i++){
                if(nums[i] != 0 && (prev == 0 || oppositeSign(nums[i], prev))){
                    max++;
                }
                if(nums[i] != 0){
                    prev = nums[i];
                }
            }
            return max == 0 ? 1 : max+1;
        }
        
        private boolean oppositeSign(int x, int y){
            return (x > 0 && y < 0) || (x < 0 && y > 0);
        }
    

Log in to reply
 

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