LeetCode 152.乘积最大子序列

it2025-03-19  21

题目描述:

给定一个整数数组 nums ,找出一个序列中乘积最大的连续子序列(该序列至少包含一个数)。 示例 1: 输入: [2,3,-2,4] 输出: 6 解释: 子数组 [2,3] 有最大乘积 6。 示例 2: 输入: [-2,0,-1] 输出: 0 解释: 结果不能为 2, 因为 [-2,-1] 不是子数组。

实现代码:

class Solution(object): def maxProduct(self, nums): """ :type nums: List[int] :rtype: int """ res=ma=mi=nums[0] for i in range(1,len(nums)): if nums[i]<0: ma,mi=mi,ma ma=max(ma*nums[i],nums[i]) mi=min(mi*nums[i],nums[i]) res=max(ma,res) return res

 

最新回复(0)