376. 摆动序列
# 376. 摆动序列 (opens new window)
# 1.贪心
每次将波峰和波谷加入作为子序列。
class Solution {
public int wiggleMaxLength(int[] nums) {
int res=1;
int inx=1;
while(inx<nums.length&&nums[inx]==nums[inx-1])inx++;
if(inx==nums.length) return 1;
boolean up=nums[inx]-nums[inx-1]>0;
while(inx<nums.length){
if(up){
while(inx<nums.length&&(nums[inx-1]<=nums[inx])){
inx++;
}
res++;
up=!up;
}
else{
while(inx<nums.length&&nums[inx-1]>=nums[inx]){
inx++;
}
res++;
up=!up;
}
}
return res;
}
}
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
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
编辑 (opens new window)
上次更新: 2023/12/15, 15:49:57