Maximum Length of Subarray With Positive Product - Problem

You're given an array of integers nums, and your task is to find the maximum length of a contiguous subarray where the product of all its elements is positive.

A subarray is a consecutive sequence of elements from the original array. For example, in the array [1, -2, 3, 0], some subarrays are [1], [1, -2], [-2, 3], and [1, -2, 3].

Key insight: A product is positive when there's an even number of negative numbers in the subarray. Zero values act as "barriers" that reset our counting since any product containing zero becomes zero.

Goal: Return the length of the longest subarray with a positive product.

Example: For nums = [1, -2, -3, 4], the subarray [1, -2, -3, 4] has product 24 > 0, so the answer is 4.

Input & Output

example_1.py โ€” Basic Case
$ Input: nums = [1, -2, -3, 4]
โ€บ Output: 4
๐Ÿ’ก Note: The entire array has product 1 ร— (-2) ร— (-3) ร— 4 = 24 > 0, so the maximum length is 4
example_2.py โ€” With Zero
$ Input: nums = [0, 1, -2, -3, 4]
โ€บ Output: 4
๐Ÿ’ก Note: Zero splits the array. The subarray [1, -2, -3, 4] has positive product 24, length 4
example_3.py โ€” All Negative
$ Input: nums = [-1, -2, -3, 0, 1]
โ€บ Output: 2
๐Ÿ’ก Note: Best subarrays are [-1, -2] and [-2, -3], both have positive product and length 2

Constraints

  • 1 โ‰ค nums.length โ‰ค 105
  • -109 โ‰ค nums[i] โ‰ค 109
  • nums[i] can be positive, negative, or zero

Visualization

Tap to expand
Dynamic Programming: Length Tracking Visualization1-2-34Ppos=1Nneg=2Ppos=3Ppos=4SWAPAlgorithm Steps1. Start: pos_len=0, neg_len=02. See +1: pos_len=1, neg_len=03. See -2: SWAP! pos_len=0, neg_len=24. See -3: SWAP! pos_len=3, neg_len=05. See +4: pos_len=4, neg_len=06. Answer: max(pos_len) = 4
Understanding the Visualization
1
Start with both runners at position 0
positive_len = 0, negative_len = 0
2
Positive number: both runners advance
Both lengths increase (if they were already running)
3
Negative number: runners swap and advance
The magic happens - positive becomes negative and vice versa
4
Zero: both runners restart
Reset both lengths to 0 - start fresh from here
Key Takeaway
๐ŸŽฏ Key Insight: We don't need to calculate actual products (which can overflow). Instead, we track the lengths of positive and negative product subarrays, swapping them when we see negative numbers!
Asked in
Google 45 Facebook 38 Amazon 32 Microsoft 28
52.3K Views
Medium-High Frequency
~18 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen