c++ easy-understanding solution with O(n) time and O(1) space, 0ms


  • 1
    S
    class Solution {
    public:
        int wiggleMaxLength(vector<int>& nums) {
            if(nums.size() < 2) return nums.size();
            int ans = 1;
            int i = 1;
            while(i < nums.size() && nums[i] == nums[i-1]) i++;
            if(i >= nums.size()) return ans;
            bool increase = nums[i] > nums[i-1];
            //ans++;
            while(i < nums.size()){
                if(increase){
                    while(i+1 < nums.size() && nums[i+1] >= nums[i])  i++;
                }
                else{
                    while(i+1 < nums.size() && nums[i+1] <= nums[i])  i++;
                }
                increase = increase? false : true;
                ans++;
                i++;
            }
            return ans;
        }
    };
    

Log in to reply
 

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