Leetcode 1690 Solution

This article provides solution to leetcode question 1690 (maximum-length-of-subarray-with-positive-product)

https://leetcode.com/problems/maximum-length-of-subarray-with-positive-product

Solution

class Solution:
    def getMaxLen(self, nums: List[int]) -> int:
        ans = 0

        pos1 = -1
        pos2 = -1
        positive_cnt = 0
        negative_cnt = 0

        for i, num in enumerate(nums):
            if num == 0:
                pos1 = i
                pos2 = -1
                negative_cnt = 0
                continue

            if num < 0:
                negative_cnt += 1

                if negative_cnt == 1:
                    pos2 = i

            if negative_cnt % 2 == 0:
                ans = max(ans, i - pos1)
            else:
                if pos2 != -1:
                    ans = max(ans, i - pos2)

        return ans