Leetcode - 376 Wiggle Subsequence (Medium)
题目描述:一大一小就构成了摆动序列,求最长的摆动序列。
Input: [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].
解题思路:up 与 down 分别表示当前位置是升序与降序时的子序列长度。
public int wiggleMaxLength(int[] nums) {
if(nums.length < 2) return nums.length;
int down = 1, up = 1;
for(int i = 1; i < nums.length; i++){
if(nums[i] > nums[i - 1]){
up = down + 1;
}else if(nums[i] < nums[i - 1]){
down = up + 1;
}
}
return Math.max(down, up);
}