leetcode-152-Maximum Product Subarray

Given an integer array nums, find the contiguous subarray within an array (containing at least one number) which has the largest product.

Example 1:

Input: [2,3,-2,4]
Output: 6
Explanation: [2,3] has the largest product 6.

Example 2:

Input: [-2,0,-1]
Output: 0
Explanation: The result cannot be 2, because [-2,-1] is not a subarray.

问题本质:
本质:动态规划问题。 局部最优,全局最优。
 product-乘法问题,存在的情况是 负数或者正数,或者从当前数开始新的连续元素相乘
 可能发生的情况: 在某个节点,继续之前的增大/减小,从此节点转折。
 所以只要在局部动态中,保持最大/最小/当前,进行判断保留即可。
应用:挖掘问题的本质,将问题抽象化, 局部:之前的值和当前值是同乡还是异向的问题,同向则被覆盖,异向则被保留。如此迭代。
class Solution:
    def maxProduct(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        final_max=max_num=min_num=nums[0]
        for num_cur in nums[1:]:
            # min_num=min(num_cur*min_num,num_cur)
            max_num_tmp=max(num_cur*min_num,num_cur*max_num)
            min_num=min(num_cur*min_num,num_cur*max_num,num_cur)
            max_num=max(max_num_tmp,num_cur)
            final_max=max(max_num,final_max)
        return final_max
if __name__=='__main__':
    st=Solution()
    num=[2,3,-2,-5,4,-5,8]
    # num=[-2,0,-1]
    # num=[2,3,-2,4]
    num=[-1,-2,-9,-6]
    out=st.maxProduct(num)
    print(out)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值