Simple C++ solution, the core idea is to skip elements that will not increase the subsequence.


  • 1
    Q
    class Solution {
    public:
        int wiggleMaxLength(vector<int>& nums) {
            
            if(nums.size()<=1) return nums.size();
            
            int dir=-1;
            int res=1;
            dir=nums[1]<nums[0]?0:dir;
            dir=nums[1]>nums[0]?1:dir;
            
            for(int i=1; i<nums.size(); i++)
            {
                if(nums[i]>nums[i-1] && dir==1 )
                {
                    res++;
                    dir=0;
                }
                else if(nums[i]<nums[i-1] && dir==0)
                {
                    res++;
                    dir=1;
                }
            }
            
            return res;
        }
    };
    

  • 0

    The code doesn't work if the first few elements in nums are the same.


Log in to reply
 

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