[
dp
array
]
Leetcode 1567. Maximum Length of Subarray With Positive Product
Problem statement
https://leetcode.com/problems/maximum-length-of-subarray-with-positive-product/
Solution
Define by pos
and neg
lengts of longest positive and negative products ending with current element.
Complexity
It is O(n)
for time and O(1)
for space.
Code
class Solution:
def getMaxLen(self, A):
ans = pos = neg = 0
for x in A:
if x > 0:
pos, neg = pos + 1, neg + 1 if neg else 0
elif x < 0:
pos, neg = 1 + neg if neg else 0, 1 + pos
else:
pos = neg = 0
ans = max(ans, pos)
return ans