C++ straight forward solution, easy to understand

  • 1

    if you draw a line to connect all points in nums, this question is asking how many turning point in the line.

    start with the second element (i = 1), find the left and right number which is different from current element. If current element is a dip or peak, then it is a turning point.

    the first element is a turning point
    the last element is a turning point too if it is different from the second last element.

    class Solution {
        int wiggleMaxLength(vector<int>& nums) 
            int size = nums.size();
            if(size<2) return size;
            int ans = 1, left, right;
            for(int i = 1; i < size; i++ )
                if(nums[i]==nums[i-1]) continue;
                left = right = i;
                while(left>0 && nums[--left]==nums[i]){};
                while(right<size-1 && nums[++right]==nums[i]){};
                if((nums[i]>nums[left] && nums[i]>nums[right])||
                    (nums[i]<nums[left] && nums[i]<nums[right])) ans++;
            if(nums[size-2]!=nums[size-1]) ans++;
            return ans;

Log in to reply

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