文章作者:Tyan
博客:noahsnail.com | CSDN |
1. Description
2. Solution
解析:Version 1,首先要将数组从所有零处断开,这样可以保证乘积一定不为0
,采用pre
来表示前一个0
所在的位置,初始状态为-1
,当碰到一个0
时,计算不包括0
在内的子数组长度m
,如果m > 0
,说明子数组不为空。要计算子数组的乘积为正数的最长长度,需要统计数组中负数的个数neg
,如果为偶数,则最长长度为子数组长度,如果为奇数,则长度应为子数组长度减去包含第一个负数在内的前一部分长度或者是从子数组开始到最后一个负数之前的长度中较大的一个。分别用start
,end
来表示第一个负数和最后一个负数的位置。遍历数组后,如果最后一个数不为0,要计算最后一个子数组。Version 2为了保证计算最后一个子数组,在nums
数组后加了一个0
。Version 3使用动态规划解决,pos[i]和neg[i]
分别表示以i
为结尾的乘积为正数的最长子数组长度和表示乘积为负数的最长子数组长度,碰到0
时重新统计。根据nums[i]
的值可以分为三种情况,nums[i] = 0
,此时pos[i]和neg[i]
都为0
;nums[i] > 0
时,pos[i] = pos[i-1] + 1
,如果neg[i-1]
为0
,则不更新neg[i]
,否则,neg[i] = neg[i-1] + 1
;nums[i] < 0
时,neg[i] = pos[i-1] + 1
,如果neg[i-1]
为0
,则不更新pos[i]
,否则,pos[i] = neg[i-1] + 1
,每次更新两个数组之后,要更新最大长度maximum = max(maximum, pos[i])
。
- Version 1
class Solution:
def getMaxLen(self, nums: List[int]) -> int:
n = len(nums)
maximum = 0
pre = -1
neg = 0
start = -1
end = -1
for i in range(n):
if nums[i] == 0:
m = i - pre - 1
if m > 0:
if neg % 2 == 0:
maximum = max(maximum, m)
else:
maximum = max(maximum, i - start - 1, end - pre - 1)
pre = i
start = -1
end = -1
neg = 0
elif nums[i] < 0:
neg += 1
if start == -1:
start = i
end = i
if pre != n - 1:
m = n - pre - 1
if m > 0:
if neg % 2 == 0:
maximum = max(maximum, m)
else:
maximum = max(maximum, n - start - 1, end - pre -1)
return maximum
- Version 2
class Solution:
def getMaxLen(self, nums: List[int]) -> int:
nums.append(0)
n = len(nums)
maximum = 0
pre = -1
neg = 0
start = -1
end = -1
for i in range(n):
if nums[i] == 0:
m = i - pre - 1
if m > 0:
if neg % 2 == 0:
maximum = max(maximum, m)
else:
maximum = max(maximum, i - start - 1, end - pre - 1)
pre = i
start = -1
end = -1
neg = 0
elif nums[i] < 0:
neg += 1
if start == -1:
start = i
end = i
return maximum
- Version 3
class Solution:
def getMaxLen(self, nums: List[int]) -> int:
n = len(nums)
pos = [0] * n
neg = [0] * n
if nums[0] > 0:
pos[0] = 1
if nums[0] < 0:
neg[0] = 1
maximum = pos[0]
for i in range(1, n):
if nums[i] > 0:
pos[i] = pos[i-1] + 1
if neg[i-1] != 0:
neg[i] = neg[i-1] + 1
elif nums[i] < 0:
if neg[i-1] != 0:
pos[i] = neg[i-1] + 1
neg[i] = pos[i-1] + 1
else:
pos[i] = 0
neg[i] = 0
maximum = max(maximum, pos[i])
return maximum
Reference
- https://leetcode.com/problems/maximum-length-of-subarray-with-positive-product/