152. 乘积最大子序列(Maximum Product Subarray)

152. 乘积最大子序列(Maximum Product Subarray)

题解

动态规划

因为有负数的存在,我们保存当前位置的最大乘积,和最小乘积,因为负数可以将最大乘积变最小,将最小变最大。

  1. 初试化结果 m a x _ r e s = M I N max\_res=MIN max_res=MIN,当前最大乘积 m a x _ n u m = 1 max\_num=1 max_num=1和当前最小乘积 m i n _ n u m = 1 min\_num=1 min_num=1

  2. 遍历数组,遍历区间 [ 0 , n ) [0,n) [0,n)

    • 若当前位置为负数 n u m s [ i ] < 0 nums[i]<0 nums[i]<0
      • 交换最大乘积和最小乘积的值
    • m a x _ n u m = m a x ( m a x _ n u m ∗ n u m s [ i ] , n u m s [ i ] ) max\_num=max(max\_num*nums[i],nums[i]) max_num=max(max_numnums[i],nums[i]),更新当前位置的最大乘积。
    • m i n _ n u m = m i n ( m i n _ n u m ∗ n u m s [ i ] , n u m s [ i ] ) min\_num=min(min\_num*nums[i],nums[i]) min_num=min(min_numnums[i],nums[i]),更新当前位置的最小乘积。
    • 更新结果 m a x _ r e s = m a x ( m a x _ n u m , m a x _ r e s ) max\_res=max(max\_num,max\_res) max_res=max(max_num,max_res)
  3. 返回 m a x _ r e s max\_res max_res

复杂度分析

  • 时间复杂度: O ( n ) O(n) O(n)
  • 空间复杂度: O ( 1 ) O(1) O(1)

Python

class Solution:
    def maxProduct(self, nums: List[int]) -> int:
        n=len(nums)
        max_res=-float("inf")
        max_num=1
        min_num=1
        for i in range(n):
            if(nums[i]<0):
                max_num,min_num=min_num,max_num
            max_num=max(max_num*nums[i],nums[i])
            min_num=min(min_num*nums[i],nums[i])
            max_res=max(max_num,max_res)
        return max_res


Java(待完成)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值