forked from AnasImloul/Leetcode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathWiggle Subsequence.cpp
More file actions
59 lines (59 loc) · 1.23 KB
/
Wiggle Subsequence.cpp
File metadata and controls
59 lines (59 loc) · 1.23 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
class Solution {
public:
int wiggleMaxLength(vector<int>& nums) {
int n=nums.size();
if(n==1){
return 1;
}
if(n==2 && nums[0]!=nums[1]){
return 2;
}
if(n==2 && nums[0]==nums[1]){
return 1;
}
char c;
int dp[n];
dp[0]=1;
int p=1;
for(p=1;p<n;p++){
if(nums[p]==nums[p-1]){
dp[p]=1;
}
else{
break;
}
}
if(p==n){
return dp[n-1];
}
if(nums[p-1]<nums[p]){
c='d';
}
else{
c='i';
}
dp[p-1]=1;
dp[p]=2;
for(int i=p+1;i<n;i++){
if(c=='d'){
if(nums[i]<nums[i-1]){
dp[i]=dp[i-1]+1;
c='i';
}
else{
dp[i]=dp[i-1];
}
}
else if(c=='i'){
if(nums[i]>nums[i-1]){
dp[i]=dp[i-1]+1;
c='d';
}
else{
dp[i]=dp[i-1];
}
}
}
return dp[n-1];
}
};