LeetCode-152、乘积最大子数组-中等

LeetCode-152、乘积最大子数组-中等

给你一个整数数组 nums ,请你找出数组中乘积最大的连续子数组(该子数组中至少包含一个数字),并返回该子数组所对应的乘积。

示例 1:

输入: [2,3,-2,4]
输出: 6
解释: 子数组 [2,3] 有最大乘积 6。

示例 2:

输入: [-2,0,-1]
输出: 0
解释: 结果不能为 2, 因为 [-2,-1] 不是子数组。

 

代码:

class Solution:
    def maxProduct(self, nums: List[int]) -> int:
        l = len(nums)
        if l == 0: return None
        if l == 1: return nums[0]
        a, b = nums[0], nums[0]
        ans = nums[0]
        for i in range(1, l):
            if nums[i] == 0:
                x = 0
                y = 0
            elif nums[i] > 0:
                if a > 0:
                    x = a * nums[i]
                    y = min(b*nums[i], nums[i])
                else:
                    x = nums[i]
                    y = b * nums[i]
            else:
                if b > 0:
                    x = nums[i]
                    y = a * nums[i]
                else:
                    x = b * nums[i]
                    y = min(a*nums[i], nums[i])
            ans = max(ans, x)
            a, b = x, y
        return ans

class Solution:
    def maxProduct(self, nums: List[int]) -> int:
        A = nums
        B = A[::-1]
        for i in range(1, len(A)):
            A[i] *= A[i - 1] or 1
            B[i] *= B[i - 1] or 1
        return max(max(A),max(B)) 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值