Leetcode 1567. Maximum Length of Subarray With Positive Product

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Maximum Length of Subarray With Positive Product

2. Solution

解析:Version 1,首先要将数组从所有零处断开,这样可以保证乘积一定不为0,采用pre来表示前一个0所在的位置,初始状态为-1,当碰到一个0时,计算不包括0在内的子数组长度m,如果m > 0,说明子数组不为空。要计算子数组的乘积为正数的最长长度,需要统计数组中负数的个数neg,如果为偶数,则最长长度为子数组长度,如果为奇数,则长度应为子数组长度减去包含第一个负数在内的前一部分长度或者是从子数组开始到最后一个负数之前的长度中较大的一个。分别用startend来表示第一个负数和最后一个负数的位置。遍历数组后,如果最后一个数不为0,要计算最后一个子数组。Version 2为了保证计算最后一个子数组,在nums数组后加了一个0。Version 3使用动态规划解决,pos[i]和neg[i]分别表示以i为结尾的乘积为正数的最长子数组长度和表示乘积为负数的最长子数组长度,碰到0时重新统计。根据nums[i]的值可以分为三种情况,nums[i] = 0,此时pos[i]和neg[i]都为0nums[i] > 0时,pos[i] = pos[i-1] + 1,如果neg[i-1]0,则不更新neg[i],否则,neg[i] = neg[i-1] + 1nums[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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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

  1. https://leetcode.com/problems/maximum-length-of-subarray-with-positive-product/
如果有收获,可以请我喝杯咖啡!