Given an integer array nums, return the length of the longest wiggle sequence.
A wiggle sequence is a sequence where the differences between successive numbers strictly alternate between positive and negative. The first difference (if one exists) may be either positive or negative. A sequence with fewer than two elements is trivially a wiggle sequence.
- For example, [1, 7, 4, 9, 2, 5] is a wiggle sequence because the differences (6, -3, 5, -7, 3) are alternately positive and negative.
- In contrast, [1, 4, 7, 2, 5] and [1, 7, 4, 5, 5] are not wiggle sequences, the first because its first two differences are positive and the second because its last difference is zero.
A subsequence is obtained by deleting some elements (eventually, also zero) from the original sequence, leaving the remaining elements in their original order.
- new solution update 2022.02.18
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21class Solution {
int dp[1001][2];
int solution(vector<int>& nums, int p, bool upper) {
if(p == nums.size()) return 0;
if(dp[p][upper] != -1) return dp[p][upper];
dp[p][upper] = 1;
for(int i = p + 1; i < nums.size(); i++) {
if((upper and nums[i] > nums[p]) or (!upper and nums[i] < nums[p])) {
dp[p][upper] = max(dp[p][upper], solution(nums, i, !upper) + 1);
}
}
return dp[p][upper];
}
public:
int wiggleMaxLength(vector<int>& nums) {
memset(dp,-1,sizeof(dp));
return max(solution(nums,0,true), solution(nums,0,false));
}
};
1 | class Solution { |