• 152乘积最大子序列


    题目:给定一个整数数组 nums ,找出一个序列中乘积最大的连续子序列(该序列至少包含一个数)。

    来源:https://leetcode-cn.com/problems/maximum-product-subarray/

    法一:别人代码

    思路:由于想用动态规划解题,通过观察数字可以发现从nums[i]到nums[i+1]的最大值之间的关系,由于有负数的存在,最大值可能直接转化为最小值,所以为了无后效性,直接把前面的最大值和最小值保存了,每次乘完后再比较。

    class Solution:
        def maxProduct(self, nums: List[int]) -> int:
            if not nums: return 
            res = nums[0]
            pre_max = nums[0]
            pre_min = nums[0]
            for num in nums[1:]:
                cur_max = max(pre_max * num, pre_min * num, num)
                cur_min = min(pre_max * num, pre_min * num, num)
                # 注意这里的最大值要另外求
                res = max(res, cur_max)
                pre_max = cur_max
                pre_min = cur_min
            return res
    if __name__ == '__main__':
        duixiang = Solution()
        # a = duixiang.maxProduct([2,3,-2,4,-9])
        # a = duixiang.maxProduct([2, 3, -2, 4])
        # b = [2,-5,-2,-4,3]
        # # b.reverse()
        # a = duixiang.maxProduct(b)
        # b = [1, -2, 0, 1, -4, 1, 1, 5, 4, -1, 6, 4, 1, -5, 0, -1, -5, 1, -6, -4]
        b = [3, -2, -3, -3, 1, 3, 0]
        b = [-1,-2,-9,-6]
        # b.reverse()
        a = duixiang.maxProduct(b)
        print(a)
    View Code

    法二:利用负数的奇偶解题

  • 相关阅读:
    《最后期限》阅读笔记03
    《最后期限》阅读笔记02
    《最后期限》阅读笔记01
    返回一个二维整数数组中最大联通子数组的和
    软件工程团队开发——第一次冲刺会议总结
    结对项目开发电梯调度
    软件工程课程建议
    第二次冲刺07
    第二次冲刺06
    第二次冲刺05
  • 原文地址:https://www.cnblogs.com/xxswkl/p/12306760.html
Copyright © 2020-2023  润新知