Maximum Length of Subarray With Positive Product - Problem

Given an array of integers nums, find the maximum length of a subarray where the product of all its elements is positive.

A subarray of an array is a consecutive sequence of zero or more values taken out of that array.

Return the maximum length of a subarray with positive product.

Input & Output

Example 1 — Mixed Signs
$ Input: nums = [1,-2,-3,4]
Output: 4
💡 Note: The entire array has positive product: 1 × (-2) × (-3) × 4 = 24 > 0, so maximum length is 4
Example 2 — With Zero
$ Input: nums = [0,1,-2,-3,-4]
Output: 3
💡 Note: Zero breaks the array. Subarray [1,-2,-3] has product 6 > 0 with length 3, which is maximum
Example 3 — All Negative
$ Input: nums = [-1,-2,-3]
Output: 2
💡 Note: Any two negatives give positive product. [-1,-2] or [-2,-3] both have length 2

Constraints

  • 1 ≤ nums.length ≤ 105
  • -109 ≤ nums[i] ≤ 109

Visualization

Tap to expand
Maximum Length of Subarray With Positive Product INPUT nums array: 1 idx 0 -2 idx 1 -3 idx 2 4 idx 3 Positive Negative Product Analysis: 1 x (-2) x (-3) x 4 = 24 (Positive!) Negative count: 2 (even) Zero count: 0 Even negatives = Positive! ALGORITHM STEPS 1 Initialize Counters pos = 0, neg = 0 Track positive/negative lengths 2 Iterate Array For each element, update pos and neg lengths 3 Handle Each Case num > 0: pos++, neg++ num < 0: swap pos/neg num = 0: reset both 4 Track Maximum maxLen = max(maxLen, pos) Update after each element Trace: pos values [1,0,1,2] --> [1,2,3,4] neg: [0,1,2,3] --> [0,1,2,3] maxLen = 4 FINAL RESULT Longest Valid Subarray: 1 -2 -3 4 Entire array is valid! Output: 4 OK - Length verified! Verification: 1*(-2)*(-3)*4 = 24 > 0 Key Insight: Track two lengths: pos (length of subarray with positive product) and neg (length with negative product). When encountering a negative number, swap pos and neg because multiplying by negative flips the sign. Zero resets both counters. Time: O(n), Space: O(1). The product of even negative numbers is positive! TutorialsPoint - Maximum Length of Subarray With Positive Product | Optimal Solution
Asked in
Amazon 25 Microsoft 18
78.0K Views
Medium Frequency
~25 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