一、题目描述
题目链接:https://leetcode-cn.com/problems/wiggle-subsequence/
二、题目分析
参考题解:https://leetcode-cn.com/problems/wiggle-subsequence/solution/bai-dong-xu-lie-by-leetcode/
看到这个题目有个大概的思路,对于每个位置,向前找到一个可以让它称为摆动数组的位置,但是因为有两个状态,向上和向下,因此一直不知道怎么写,看完题解之后忍不住妙了出来。
假设输入为nums[i],题解使用两个数组来辅助解答,一个为up,一个为dowm,up[i]代表在nums[i] - [i-1]为正数时,最后两位为上升数组可以达到的最长摆动数组,dowm[i]代表在nums[i] - [i-1]为负数时,最后两位为下降数组可以达到的最长摆动数组。若我们判断的nums[i] - [i-1]为正数,则up[i] = dowm[i-1] + 1。
三、代码
链接:https://leetcode-cn.com/problems/wiggle-subsequence/solution/bai-dong-xu-lie-by-leetcode/
public class Solution {
public int wiggleMaxLength(int[] nums) {
if (nums.length < 2)
return nums.length;
int[] up = new int[nums.length];
int[] down = new int[nums.length];
up[0] = down[0] = 1;
for (int i = 1; i < nums.length; i++) {
if (nums[i] > nums[i - 1]) {
up[i] = down[i - 1] + 1;
down[i] = down[i - 1];
} else if (nums[i] < nums[i - 1]) {
down[i] = up[i - 1] + 1;
up[i] = up[i - 1];
} else {
down[i] = down[i - 1];
up[i] = up[i - 1];
}
}
return Math.max(down[nums.length - 1], up[nums.length - 1]);
}
}
链接:https://leetcode-cn.com/problems/wiggle-subsequence/solution/bai-dong-xu-lie-by-leetcode/
// 优化,因为我们每次只用到i-1,因此可以只用两个变量保存
public class Solution {
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);
}
}