problem
376. Wiggle Subsequence
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 one element and a sequence with two non-equal elements are trivially wiggle sequences.
- For example, [1, 7, 4, 9, 2, 5] is a wiggle sequence because the differences (6, -3, 5, -7, 3) alternate between positive and negative.
- In contrast, [1, 4, 7, 2, 5] and [1, 7, 4, 5, 5] are not wiggle sequences. The first is not because its first two differences are positive, and the second is not because its last difference is zero.
A subsequence is obtained by deleting some elements (possibly zero) from the original sequence, leaving the remaining elements in their original order.
Given an integer array nums, return the length of the longest wiggle subsequence of nums.
Example 1:
Input: nums = [1,7,4,9,2,5]
Output: 6
Explanation: The entire sequence is a wiggle sequence with differences (6, -3, 5, -7, 3).
Example 2:
Input: nums = [1,17,5,10,13,15,10,5,16,8]
Output: 7
Explanation: There are several subsequences that achieve this length.
One is [1, 17, 10, 13, 10, 16, 8] with differences (16, -7, 3, -3, 6, -8).
Example 3:
Input: nums = [1,2,3,4,5,6,7,8,9]
Output: 2
approach 1 Brute force
class Solution {
public:
vector<int> num1;
int helper(int idx, bool up){
int maxs = 0;
for(int i=idx+1; i<num1.size(); i++){
if((up && num1[i]-num1[idx]>0) || (!up && num1[i]-num1[idx]<0))
maxs = max(maxs, 1 + helper(i, !up));
}
return maxs;
}
int wiggleMaxLength(vector<int>& nums) {
num1 = nums;
if(nums.size() < 2) return nums.size();
return 1 + max(helper(0, true), helper(0, false));
}
};
approach 2 DP
class Solution {
public:
int wiggleMaxLength(vector<int>& nums) {
if(nums.size() < 2)return nums.size();
vector<int> up(nums.size(), 1), down(nums.size(), 1);
for(int i=1; i<nums.size(); i++){
for(int j=0; j<i; j++){
if(nums[i] > nums[j])
up[i] = max(up[i], down[j] + 1);
else if(nums[i] < nums[j])
down[i] = max(down[i], up[j] + 1);
}
}
return max(up[nums.size()-1], down[nums.size()-1]);
}
};
approach 3 linear DP
approach 4 Greedy
class Solution {
public:
int wiggleMaxLength(vector<int>& nums) {
if(nums.size() < 2) return nums.size();
int prediff = nums[1] - nums[0];
int cnt = prediff == 0 ? 1 : 2;
for(int i=2; i<nums.size(); i++){
int diff = nums[i] - nums[i-1];
if( (diff > 0 && prediff <=0) || (diff < 0 && prediff >= 0)){
cnt++;
prediff = diff;
}
}
return cnt;
}
};

给定整数数组nums,找出最长的摆动子序列的长度。摆动序列是指连续数列中相邻元素之间的差值交替为正和负。例如,[1, 7, 4, 9, 2, 5] 是一个摆动序列,而 [1, 4, 7, 2, 5] 不是,因为它的最后一个差值为零。"
112893121,10293228,Vue项目中引入本地资源及常见问题解析,"['前端开发', 'Vue', 'Vue CLI', '资源管理']
683

被折叠的 条评论
为什么被折叠?



