如果连续数字之间的差严格地在正和负之间交替,则这样的数字序列称为摆动序列。 第一个差值(如果存在)可以是正的也可以是负的。 少于两个元素的序列通常是摆动序列。
例如,[1,7,4,9,2,5]
是一个摆动序列,因为连续数字的差(6,-3,5,-7,3)
交替为正和负。 相反,[1,4,7,2,5]
和[1,7,4,5,5]
不是摆动序列,第一个是因为它的前两个连续数字的差是正的,而第二个是因为它的最后一个连续数字的差零。
给定一个整数序列,返回作为摆动序列的最长子序列的长度。 通过从原始序列中删除一些元素(和0)来获得子序列,使剩余元素保持其原始顺序。
样例
例1:
输入: [1,7,4,9,2,5]
输出: 6
解释: 整个序列都是一个摆动序列。
例2:
输入: [1,17,5,10,13,15,10,5,16,8]
输出: 7
解释: 有若干个摆动子序列都满足这个长度。 其中一个为[1,17,10,13,10,16,8]。
挑战
尝试用O(n)时间复杂度完成。
解题思路1:
动态规划。是Lintcode 76. 最长上升子序列的升级版。
dp[i]表示以i下标结尾的序列中最长摆动序列的长度,由于需要知道之前元素的上升下降趋势,所以新建一个数组wiggle[i]用来标记以i下标结尾是上升还是下降,true代表上升,false代表下降
public class Solution {
/**
* @param nums: the given sequence
* @return: the length of the longest subsequence that is a wiggle sequence
*/
public int wiggleMaxLength(int[] nums) {
// Write your code here
if(nums.length < 2)
return 1;
//dp[i]表示以i下标结尾的序列中最长摆动序列的长度
int[] dp = new int[nums.length];
//标记以i下标结尾是上升还是下降,true代表上升,false代表下降
boolean[] wiggle = new boolean[nums.length];
int res = 0;
//初始条件,由于2个元素也符合摆动序列的定义,所以将所有i>1的dp[i]初始化为2。同时初始化wiggle[1]
dp[0] = 1;
for(int i=1; i<nums.length; i++)
dp[i] = 2;
wiggle[1] = nums[1] > nums[0] ? true : false;
//递推式
for(int i=2; i<nums.length; i++){
//标记当前点的趋势是上升还是下降,若相等则continue
if(nums[i] > nums[i-1])
wiggle[i] = true;
else if(nums[i] < nums[i-1])
wiggle[i] = false;
else
continue;
for(int j=1; j<i; j++)
if(wiggle[j] != wiggle[i])
dp[i] = Math.max(dp[i], dp[j]+1);
res = Math.max(res, dp[i]);
}
return res;
}
}
解题思路2:
贪心。
public class Solution {
/**
* @param nums: the given sequence
* @return: the length of the longest subsequence that is a wiggle sequence
*/
public int wiggleMaxLength(int[] nums) {
// Write your code here
if (nums == null || nums.length == 0)
return 0;
int up = 1, 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.max(up, down);
}
}