20 lines O(n) greedy java solution, easy to understand


  • 2
    B

    0_1472870111140_1870641572.jpg

    The main idea is finding how many edges which are different direction next to each others in the this problem.

    I initialize the dir with -2, means anywhere.

    public class Solution {
        public int wiggleMaxLength(int[] nums) {
            if(nums.length < 2)return nums.length; 
            int dir = -2; 
            int count = 1;
            for(int i = 1;i< nums.length;i++){
                if(nums[i-1] < nums[i]){
                   if(dir == 1){continue;}
                   else {dir = 1; count++; }
                   
                }
                
                else if(nums[i-1] > nums[i]){
                    if(dir == -1){continue;}
                    else{dir = -1; count++;}
                }
            }
            return count;
        }
    }
    

Log in to reply
 

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