# My C++ soulution and explaination

• Find the first two different numbers, set pre=-sign(nums[i]-nums[i-1]), ans=1.
Only cur*pre=-1, then ans++
For example, [1, 3, 2, 2, 4, 5, 1]
set pre=-1, because 1<3.
[1, 3] => cur=1, pre=1; ans >> 2
[1, 3, 2] => cur=-1, pre=-1; ans >> 3
[1, 3, 2, 2] =>cur=0, Do not change pre=-1 ans >> 3
[1, 3, 2, 2, 4] =>cur=1, pre=1; ans >> 4
[1, 3, 2, 2, 4, 5] =>cur=1, pre=1; ans >> 4
[1, 3, 2, 2, 4, 5, 1] =>cur=-1; ans >> 5

``````class Solution {
int helper(int i,int j)
{
if(i<j) return -1;
else if(i>j) return 1;
else return 0;
}
public:
int wiggleMaxLength(vector<int>& nums) {
int n=nums.size();
if(n<2) return n;
int ans=1;
int i,pre,cur;
//First, find the fist two numbers who are different.
for(i=1;i<n;i++)
{
if(nums[i]!=nums[i-1])
break;
}
pre=-helper(nums[i-1],nums[i]);
for( i=i-1;i<n;i++)
{
cur=helper(nums[i-1],nums[i]);
if(cur*pre<0) ans++;
if(cur!=0)
pre=cur;
}
return ans;
}
};
``````

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