C++ Simple O(N) Solution


  • 0
    H
    int wiggleMaxLength(vector<int>& nums) {
            int n = nums.size();
            int i = 1;
            while (i < n && nums[i] == nums[i-1]) i++;
            if (i >= n) return min(1, n);
            bool less = nums[i] < nums[i-1];
            int res = 1;
            for (; i < n; i++) {
                if ((nums[i] < nums[i-1] && less) || (nums[i] > nums[i-1] && !less)) {
                    res++;
                    less = !less;
                }
            }
            return res;
        }
    

Log in to reply
 

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