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.
Examples:
Input: [1,7,4,9,2,5] Output: 6 The entire sequence is a wiggle sequence. Input: [1,17,5,10,13,15,10,5,16,8] Output: 7 There are several subsequences that achieve this length. One is [1,17,10,13,10,16,8]. Input: [1,2,3,4,5,6,7,8,9] Output: 2
Follow up:
Can you do it in O(n) time?
该题目的意思是:
给定一个数组序列,把所有相邻的前面数字减去前面,得到一个正数或者负数或者为0,
1、如果这个数组序列中从第一个到最后一个数中,相邻数字之差是正负交替的,则认为是wiggle序列
2、如果有相邻数字之差为0, 则不是wiggle序列
3、单个元素是wiggle序列,长度为1
如果在数组序列中去掉某些元素形成的自序列,能够同时满足条件1、2、3,则该子数组是wiggle序列
求给定数组,能够形成wiggle序列的最长子数组
解法分析:
1、因为一个给定数组的具有相同wiggle序列长度的子序列可能有多个,我们可以认为第一个元素一定在wiggle序列中,这样一段固定会更容易求解
2、定义两个数组up[size]和down[size],分别表示最后一个相邻差为正和负时,wiggle序列的长度
例如: up[i]表示数组nums(0, i)的最长wiggle序列,并且wiggle序列中最后一个元素和倒数第二个元素之差为正
down[i]表示数组nums(0, i)的最长wiggle序列,并且wiggle序列中最后一个元素和倒数第二个元素之差为负
3、可以从前往后遍历待计算的数组,对于i属于(1, size-1)
对于当前第i+1个元素(i是数组下标),
A、如果nums[i] > nums[i-1], 那么up[i] = down[i-1] + 1, down[i] = down[i-1]
B、如果nums[i] < nums[i-1], 那么up[i] = down[i-1], down[i] = up[i-1] + 1
C、如果nums[i] = nums[i-1], 那么up[i] = up[i-1], down[i] = down[i-1]
最后max(up[size-1], down[size-1])即是所求解
【AC代码】
参考资料
https://discuss.leetcode.com/topic/52052/c-0ms-o-n-dynamic-programming-solution/2