Skip to content

1567. Maximum Length of Subarray With Positive Product 👍

  • Time: $O(n)$;
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
 public:
  int getMaxLen(vector<int>& nums) {
    int ans = 0;
    // the maximum length of subarrays ending in `num` with a negative product
    int neg = 0;
    // the maximum length of subarrays ending in `num` with a positive product
    int pos = 0;

    for (const int num : nums) {
      pos = num == 0 ? 0 : pos + 1;
      neg = num == 0 || neg == 0 ? 0 : neg + 1;
      if (num < 0)
        swap(pos, neg);
      ans = max(ans, pos);
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
  public int getMaxLen(int[] nums) {
    int ans = 0;
    // the maximum length of subarrays ending in `num` with a negative product
    int neg = 0;
    // the maximum length of subarrays ending in `num` with a positive product
    int pos = 0;

    for (final int num : nums) {
      pos = num == 0 ? 0 : pos + 1;
      neg = num == 0 || neg == 0 ? 0 : neg + 1;
      if (num < 0) {
        final int temp = pos;
        pos = neg;
        neg = temp;
      }
      ans = Math.max(ans, pos);
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution:
  def getMaxLen(self, nums: list[int]) -> int:
    ans = 0
    # the maximum length of subarrays ending in `num` with a negative product
    neg = 0
    # the maximum length of subarrays ending in `num` with a positive product
    pos = 0

    for num in nums:
      pos = 0 if num == 0 else pos + 1
      neg = 0 if num == 0 or neg == 0 else neg + 1
      if num < 0:
        pos, neg = neg, pos
      ans = max(ans, pos)

    return ans