A sequence of numbers is called a wiggle sequence if 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.
Given a sequence of integers, return the length of the longest subsequence that is a wiggle sequence. A subsequence is obtained by deleting some number of elements (eventually, also zero) from the original sequence, leaving the remaining elements in their original order.
给出一个数组,让判断最长的摇摆子序列长度,即元素保持一升一降
思路:
greedy 或者dp
感觉greedy也可以说是简化版的dp
记录下两个方向up和down,用变量表示,(dp的话就是保存下所有的up,down值,数组长度)
初始状态up,down都是1
比如[1,2,3,4,2]
刚开始到2的时候上升,所以up=down + 1 = 2
然后3和4的时候一路上升,因为只是上升,趋势没有变,down仍然停留在1,up由down决定,也不变
后面到最后一个2的时候,下降,下降次数由上一个上升次数决定,down=up+1
(因为是摇摆序列,没有上升就没有下降,没有下降就没有上升)
注意当数组长度是0的时候,因为up和down初始值都是1,所以取min(n, max(up, down))
public int wiggleMaxLength(int[] nums) {
if (nums == null) {
return 0;
}
int up = 1;
int down = 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.min(nums.length, Math.max(up, down));
}