[LeetCode] 376. Wiggle Subsequence @ python

本文探讨了如何求解数组中最长摆动子序列的问题,通过动态规划的方法,详细介绍了两种算法实现,一种时间复杂度为O(N^2),另一种优化至O(N),并附带代码示例。

一.题目:
如果一个数组里面,相邻的两个数字的差是正负交替的,那么认为这个是波动序列。求输入的数组里面最长的波动序列长度。<摆动子序列问题>
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]为减的最大摆动序列长度.
图解如下:
dp数组更新过程
代码如下:(时间复杂度为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])
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值