📅  最后修改于: 2023-12-03 15:36:02.106000             🧑  作者: Mango
给定一个长度为n的整数数组nums,找到一个乘积为0的最长子数组,并返回该子数组的长度。如果不存在乘积为0的子数组,则返回0。
输入:
nums = [1,0,2,3,0,6,7,8,0,4,5]
输出:
5
解释:
子数组[0,6,7,8,0]的乘积为0,且是最长的满足条件的子数组,长度为5。
遍历一遍输入数组,同时记录一下当前乘积并更新最大值和最小值,如果出现当前乘积为0的情况,那么乘积为0的子数组的长度就是当前下标+1。如果出现当前值为0的情况,则需要将最大值和最小值都赋值为1,否则会影响后面的计算。遍历完成后返回最大乘积即可。
def maxProduct(nums: List[int]) -> int:
max_product = float('-inf')
current_max = 1
current_min = 1
for num in nums:
# 交换最大值和最小值,因为负数会让最小值变成最大值
if num < 0:
current_max, current_min = current_min, current_max
current_max = max(current_max * num, num)
current_min = min(current_min * num, num)
max_product = max(max_product, current_max)
# 如果遇到0,需要将最大值和最小值都重置为1
if num == 0:
current_max = current_min = 1
return max_product if max_product != float('-inf') else 0
该算法遍历了一遍输入数组,时间复杂度为$O(n)$。
该算法只使用了常量级别的额外空间,空间复杂度为$O(1)$。