Simple C++ solution, O(n) time and O(1) space complexity


  • 0
    M
    class Solution {
    public:
        int wiggleMaxLength(vector<int>& nums) {
            if(nums.size() < 2)
                return nums.size();
            int i=0, sign = 0, result = 1;
            for(; i<nums.size()-1; i++){
                if(nums[i] == nums[i+1])
                    continue;
                else if(nums[i] > nums[i+1]){
                    if(sign == 0){
                        result++;
                        sign = 1;
                    }
                    else if(sign == 1) continue;
                    else{
                        result++;
                        sign = 1;
                    }
                }
                else{
                    if(sign == 0){
                        result++;
                        sign = -1;
                    }
                    else if(sign == -1) continue;
                    else{
                        result++;
                        sign = -1;
                    }
                }
            }
            return result;
        }
    };
    

Log in to reply
 

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