• Maximum Product Subarray


    Find the contiguous subarray within an array (containing at least one number) which has the largest product.

    For example, given the array [2,3,-2,4],
    the contiguous subarray [2,3] has the largest product = 6.

    总结来说对于subarray的题目要使用prefix sum或者prefix product比较合适。1.但是是先计算一轮prefix sum,之后再处理如Subarray Sum Closet.2.或者像Subarray Sum这样的使用DP local,global, 计算以每个位置结束的子数组最大值(也就是求局部的prefix sum). 总体思路只有这两种,具体选哪个按照题意定。

    这题如果求出prefix product,之后想要用求解还是得枚举开始和结束位,复杂度位O(n^2),考虑第二种思路。

    因为存在符号问题,我的直观思路是维护一个正的最大值和一个负的最小值,但是这样操作要做的判读非常多。考虑为正的最小值不会对结果有影响(乘以正数小于正的最大值乘以正数,乘以负数大于正的最大值乘以负数,无法更新正的最大值和负的最小值),为负的最大值同理。所以这里可以总体考虑最大值和最小值忽略符号的影响。代码如下:

    class Solution(object):
        def maxProduct(self, nums):
            """
            :type nums: List[int]
            :rtype: int
            """
            if not nums:
                return 0
            global_max = nums[0]
            local_min = nums[0]
            local_max = nums[0]
            for i in xrange(1, len(nums)):
                local_min_now = min(min(local_min*nums[i], local_max*nums[i]), nums[i])
                local_max_now = max(max(local_max*nums[i], local_min*nums[i]), nums[i])
                global_max = max(global_max, local_max_now)
                local_min = local_min_now
                local_max = local_max_now
            return global_max

    这题还需再看。

  • 相关阅读:
    WPF 模拟UI 键盘录入
    rabbitmq使用dead letter机制来进行retry
    工厂设计模式
    python 内置速度最快算法(堆排)
    简单工厂设计模式
    杂类
    MorkDown 常用语法总结
    使用python列表推导式进行99乘法表
    linux 命令free -m 命令结果分析
    理解记忆三种常见字符编码:ASCII, Unicode,UTF-8
  • 原文地址:https://www.cnblogs.com/sherylwang/p/5697495.html
Copyright © 2020-2023  润新知