Skip to content

Commit 2a32768

Browse files
authored
Create maximum-length-of-subarray-with-positive-product.py
1 parent 3c736cd commit 2a32768

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
# Time: O(n)
2+
# Space: O(1)
3+
4+
class Solution(object):
5+
def getMaxLen(self, nums):
6+
"""
7+
:type nums: List[int]
8+
:rtype: int
9+
"""
10+
result, neg_cnt, last_zero_pos, first_valid_neg_pos = 0, 0, -1, -1
11+
for i in xrange(len(nums)):
12+
if nums[i] == 0:
13+
neg_cnt = 0
14+
last_zero_pos = i
15+
first_valid_neg_pos = -1
16+
continue
17+
if nums[i] < 0:
18+
if first_valid_neg_pos == -1:
19+
first_valid_neg_pos = i
20+
neg_cnt += 1
21+
result = max(result, i-(last_zero_pos if neg_cnt%2 == 0 else first_valid_neg_pos))
22+
return result

0 commit comments

Comments
 (0)