一.题目:
如果一个数组里面,相邻的两个数字的差是正负交替的,那么认为这个是波动序列。求输入的数组里面最长的波动序列长度。<摆动子序列问题>
Example 1:
Input: [1,7,4,9,2,5]
Output: 6
Explanation: The entire sequence is a wiggle sequence.
Example 2:
Input: [1,17,5,10,13,15,10,5,16,8]
Output: 7
Explanation: There are several subsequences that achieve this length. One is [1,17,10,13,10,16,8].
Example 3:
Input: [1,2,3,4,5,6,7,8,9]
Output: 2
二.解题思路:
输入数组为nums,我们定义了一个记录递增的DP数组inc,一个记录递减的DP数组dec,其中inc[i]和dec[i]分别代表以i结尾且当前值nums[i]为增的最大摆动序列长度,和以i结尾的且当前值nums[i]为减的最大摆动序列长度.
图解如下:

代码如下:(时间复杂度为O(N^2),空间复杂度为O(N))
class Solution(object):
def wiggleMaxLength(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
n = len(nums)
if n <= 1:
return n
inc, dec = [1] * n, [1] * n
for x in range(n):
for y in range(x):
if nums[x] > nums[y]:
inc[x] = max(inc[x], dec[y] + 1)
elif nums[x] < nums[y]:
dec[x] = max(dec[x], inc[y] + 1)
return max(inc[-1], dec[-1])
要优化成时间复杂度O(N)的话,我们可以观察在上述代码中其实不需要从头遍历,只需要知道上一个元素对应的最长递增和递减数组即可。
代码如下:
class Solution(object):
def wiggleMaxLength(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
n = len(nums)
if n <= 1:
return n
inc, dec = [1] * n, [1] * n
for x in range(1, n):
if nums[x] > nums[x - 1]:
inc[x] = dec[x - 1] + 1
dec[x] = dec[x - 1]
elif nums[x] < nums[x - 1]:
inc[x] = inc[x - 1]
dec[x] = inc[x - 1] + 1
else:
inc[x] = inc[x - 1]
dec[x] = dec[x - 1]
return max(inc[-1], dec[-1])
本文探讨了如何求解数组中最长摆动子序列的问题,通过动态规划的方法,详细介绍了两种算法实现,一种时间复杂度为O(N^2),另一种优化至O(N),并附带代码示例。
669

被折叠的 条评论
为什么被折叠?



