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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code