Maximum Length of Subarray With Positive Product Problem
Description
LeetCode Problem 1567.
Given an array of integers nums, find the maximum length of a subarray where the product of all its elements is positive.
A subarray of an array is a consecutive sequence of zero or more values taken out of that array.
Return the maximum length of a subarray with positive product.
Example 1:
Input: nums = [1,-2,-3,4]
Output: 4
Explanation: The array nums already has a positive product of 24.
Example 2:
Input: nums = [0,1,-2,-3,-4]
Output: 3
Explanation: The longest subarray with positive product is [1,-2,-3] which has a product of 6.
Notice that we cannot include 0 in the subarray since that'll make the product 0 which is not positive.
Example 3:
Input: nums = [-1,-2,-3,0,1]
Output: 2
Explanation: The longest subarray with positive product is [-1,-2] or [-2,-3].
Constraints:
1 <= nums.length <= 10^5-10^9 <= nums[i] <= 10^9
Solution
Approach: Track Positive and Negative Lengths
Only the signs matter, and a zero kills any subarray that contains it. For each position keep two numbers about subarrays that end there:
pos: the length of the longest one with a positive product,neg: the length of the longest one with a negative product,
with 0 meaning there is none. Move right one value x at a time:
x > 0: the signs stay the same.posgrows by one (a lonexis positive too), andneggrows by one only if there was a negative subarray to extend.x < 0: the signs swap. The newposisneg + 1ifneg > 0, else0; the newnegispos + 1.x == 0: both become0.
The answer is the largest pos seen. The tricky part is the "only if it exists" rule: if there is no negative subarray ending at the previous position, a positive x cannot create one, and a negative x cannot create a positive one.
Complexity: O(n) time and O(1) extra space.
class Solution:
def getMaxLen(self, nums: List[int]) -> int:
# pos / neg: longest subarray ending here with a positive / negative product (0 if none)
pos = neg = best = 0
for x in nums:
if x > 0:
pos, neg = pos + 1, (neg + 1 if neg else 0)
elif x < 0:
pos, neg = (neg + 1 if neg else 0), pos + 1
else:
pos = neg = 0 # no subarray through a zero has a nonzero product
best = max(best, pos)
return best