Easy Greedy O(n) Solution


  • 0
    J
     int wiggleMaxLength(vector<int>& nums) {
            int n = nums.size();
            if(n < 2) return n;
            
            int i = 1;
            
            while(i < n && nums[i] == nums[i - 1]) i++;
            
            if(i == n) return 1;
            
            int ans = 2;
            bool inc = nums[i - 1] < nums[i];
            
            while(i < n) {
                if((inc && nums[i] < nums[i - 1]) || (!inc && nums[i] > nums[i - 1])) {
                    ans++;
                    inc = !inc;
                }
                
                i++;
            }
            
            return ans;
        }
    

Log in to reply
 

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