|
| 1 | +""" |
| 2 | +Problem Link: https://leetcode.com/problems/maximum-length-of-subarray-with-positive-product/ |
| 3 | + |
| 4 | +Given an array of integers nums, find the maximum length of a subarray where the product of all its elements is positive. |
| 5 | +A subarray of an array is a consecutive sequence of zero or more values taken out of that array. |
| 6 | +Return the maximum length of a subarray with positive product. |
| 7 | + |
| 8 | +Example 1: |
| 9 | +Input: nums = [1,-2,-3,4] |
| 10 | +Output: 4 |
| 11 | +Explanation: The array nums already has a positive product of 24. |
| 12 | + |
| 13 | +Example 2: |
| 14 | +Input: nums = [0,1,-2,-3,-4] |
| 15 | +Output: 3 |
| 16 | +Explanation: The longest subarray with positive product is [1,-2,-3] which has a product of 6. |
| 17 | +Notice that we cannot include 0 in the subarray since that'll make the product 0 which is not positive. |
| 18 | + |
| 19 | +Example 3: |
| 20 | +Input: nums = [-1,-2,-3,0,1] |
| 21 | +Output: 2 |
| 22 | +Explanation: The longest subarray with positive product is [-1,-2] or [-2,-3]. |
| 23 | + |
| 24 | +Example 4: |
| 25 | +Input: nums = [-1,2] |
| 26 | +Output: 1 |
| 27 | + |
| 28 | +Example 5: |
| 29 | +Input: nums = [1,2,3,5,-6,4,0,10] |
| 30 | +Output: 4 |
| 31 | + |
| 32 | +Constraints: |
| 33 | +1 <= nums.length <= 10^5 |
| 34 | +-10^9 <= nums[i] <= 10^9 |
| 35 | +""" |
| 36 | +class Solution: |
| 37 | + def getMaxLen(self, nums: List[int]) -> int: |
| 38 | + cur_positive = cur_negative = max_len = 0 |
| 39 | + |
| 40 | + for num in nums: |
| 41 | + if num == 0: |
| 42 | + cur_positive = cur_negative = 0 |
| 43 | + elif num < 0: |
| 44 | + cur_positive, cur_negative = (0 if cur_negative == 0 else cur_negative + 1), cur_positive + 1 |
| 45 | + else: |
| 46 | + cur_positive += 1 |
| 47 | + cur_negative = (0 if cur_negative == 0 else cur_negative + 1) |
| 48 | + |
| 49 | + max_len = max(max_len, cur_positive) |
| 50 | + |
| 51 | + return max_len |
0 commit comments