medium Maximum Length of Subarray With Positive Product
Problem Statement
Given an integer array nums, find the maximum length of a subarray where the product of all its elements is greater than 0.
A subarray is a sequence of consecutive elements from the original array.
Examples
-
Example 1:
- Input:
nums = [1, -2, 3, 4] - Expected Output:
2 - Justification: The longest subarray with a positive product is
[3, 4], with a length of 2.
- Input:
-
Example 2:
- Input:
nums = [-1, -2, -3, -4] - Expected Output:
4 - Justification: The entire array produces a positive product since an even number of negative numbers multiply to a positive product. Hence, the longest length is 4.
- Input:
-
Example 3:
- Input:
nums = [0, -1, 2, -3, 4, -5, 6] - Expected Output:
5 - Justification: The longest subarray with a positive product is
[2, -3, 4, -5, 6], with a length of 5.
- Input:
Try it yourself
Try solving this question here:
✅ Solution Maximum Length of Subarray With Positive Product
Problem Statement
Given an integer array nums, find the maximum length of a subarray where the product of all its elements is greater than 0.
A subarray is a sequence of consecutive elements from the original array.
Examples
-
Example 1:
- Input:
nums = [1, -2, 3, 4] - Expected Output:
2 - Justification: The longest subarray with a positive product is
[3, 4], with a length of 2.
- Input:
-
Example 2:
- Input:
nums = [-1, -2, -3, -4] - Expected Output:
4 - Justification: The entire array produces a positive product since an even number of negative numbers multiply to a positive product. Hence, the longest length is 4.
- Input:
-
Example 3:
- Input:
nums = [0, -1, 2, -3, 4, -5, 6] - Expected Output:
5 - Justification: The longest subarray with a positive product is
[2, -3, 4, -5, 6], with a length of 5.
- Input:
Solution
To solve this problem, we maintain a length of the longest subarray while traversing through the array once. Our approach relies on understanding how the sign of the product changes with each element. Specifically, a positive number doesn't change the product's sign, a negative number flips it, and zero resets it. Hence, we track the length of the subarray until the current position that leads to a positive and negative product separately, updating them based on the current number's sign.
This method is effective because it simplifies the problem to tracking the sign changes due to negative numbers and resets caused by zeros, which can be done in a single pass through the array. By keeping track of the lengths of subarrays that lead to both positive and negative products, we can efficiently find the maximum length of the subarray with a positive product without needing to calculate the actual products or examine every possible subarray explicitly.
Step-by-Step Algorithm
- Initialize two counters:
positiveCountto 0 andnegativeCountto 0. These track the length of the longest subarray ending at the current index with a positive and negative product, respectively. - Initialize
maxLengthto 0 to keep track of the maximum length of subarrays with positive products. - Iterate through the array
nums:-
If the current element is positive, increment
positiveCountby 1. IfnegativeCountis not 0, increment it by 1 as well, since a negative product can become positive if multiplied by a negative number. -
If the current element is negative, swap
positiveCount + 1andnegativeCountif value ofnegativeCountis 0. Otherwise, swappositiveCount + 1andnegativeCount + 1. -
If the current element is zero, reset both
positiveCountandnegativeCountto 0 since the product of any subarray containing zero is zero. -
Update
maxLengthwith the maximum value between itself andpositiveCount.
-
- The answer is the value of
maxLengthafter iterating through the entire array.
Algorithm Walkthrough
Let's consider the input [0, -1, 2, -3, 4, -5, 6].
-
Initialization:
positiveCount = 0: Tracks the length of the current subarray with a positive product.negativeCount = 0: Tracks the length of the current subarray with a negative product.maxLength = 0: Keeps track of the maximum length of any subarray encountered with a positive product.
-
First Element (0):
- The first element is
0, which resets bothpositiveCountandnegativeCountto0. positiveCount = 0,negativeCount = 0.maxLengthremains0.
- The first element is
-
Second Element (-1):
- The second element is
-1, a negative number. - Swap
positiveCountandnegativeCount(both are0at this point, so swapping has no effect). - Increment
negativeCountby 1:negativeCount = 1. positiveCountremains0.maxLengthremains0(since there's no positive product subarray yet).
- The second element is
-
Third Element (2):
- The third element is
2, a positive number. - Increment
positiveCount(since it's positive):positiveCount = 1. - Increment
negativeCount(since a negative subarray exists):negativeCount = 2. - Update
maxLengthto1.
- The third element is
-
Fourth Element (-3):
- The fourth element is
-3, a negative number. - Swap
positiveCount + 1andnegativeCount + 1then incrementnegativeCount:positiveCountbecomes3andnegativeCountbecomes2. - Increment
negativeCountby 1:negativeCount = 2. - Update
maxLengthto2(the length of subarray leading up to the second element).
- The fourth element is
-
Fifth Element (4):
- The fifth element is
4, a positive number. - Increment
positiveCount:positiveCount = 4. - Increment
negativeCount(since a negative subarray exists):negativeCount = 3. - Update
maxLengthto4.
- The fifth element is
-
Sixth Element (-5):
- The sixth element is
-5, a negative number. - Swap
positiveCount + 1andnegativeCount + 1then incrementnegativeCount:positiveCountbecomes4andnegativeCountbecomes5. - Increment
negativeCountby 1:negativeCount = 5. maxLengthremains4.
- The sixth element is
-
Seventh Element (6):
- The seventh element is
6, a positive number. - Increment
positiveCount:positiveCount = 5. - Increment
negativeCount(since a negative subarray exists):negativeCount = 6. - Update
maxLengthto5.
- The seventh element is
-
Final Output:
- After processing all elements, the
maxLengthfound is5.
- After processing all elements, the
Code
public class Solution {
public int getMaxLen(int[] nums) {
int positiveCount = 0, negativeCount = 0, maxLength = 0;
for (int num : nums) {
if (num > 0) {
// Positive number found
positiveCount++; // Increase length of subarray with positive product
negativeCount = negativeCount == 0 ? 0 : negativeCount + 1; // Increase only if there's already a negative product
} else if (num < 0) {
// Negative number found
int temp = positiveCount;
positiveCount = negativeCount == 0 ? 0 : negativeCount + 1; // Swap counts, increase positiveCount if negativeCount was non-zero
negativeCount = temp + 1; // Increase negativeCount
} else {
// Zero found, reset counts
positiveCount = 0;
negativeCount = 0;
}
maxLength = Math.max(maxLength, positiveCount); // Update maxLength
}
return maxLength;
}
public static void main(String[] args) {
Solution solution = new Solution();
// Test the algorithm with new examples
System.out.println(solution.getMaxLen(new int[] { 1, -2, 3, 4 })); // Expected Output: 2
System.out.println(solution.getMaxLen(new int[] { -1, -2, -3, -4 })); // Expected Output: 4
System.out.println(
solution.getMaxLen(new int[] { 0, -1, 2, -3, 4, -5, 6 })
); // Expected Output: 5
}
}
Complexity Analysis
-
Time Complexity:
where nis the number of elements in the array. This is because the algorithm iterates through the array exactly once, performing a constant amount of work for each element. -
Space Complexity:
as the space required does not grow with the size of the input array. Only a fixed number of variables are used, regardless of the array size.
🤖 Don't fully get this? Learn it with Claude
Stuck on Maximum Length of Subarray With Positive Product? Open Claude, copy a block below, and it'll teach you this exact concept — visually and interactively.
Progressively stronger hints — you still solve it.
I'm working on the problem **Maximum Length of Subarray With Positive Product** (DSA). Give me a HINT LADDER: start with the tiniest nudge, then wait. Only reveal the next, stronger hint when I ask. Do NOT show the full solution unless I type 'show solution'. Keep me doing the thinking. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
See the technique, not just code.
Explain the optimal approach to **Maximum Length of Subarray With Positive Product** with a VISUAL walkthrough: trace it on a small concrete example using ASCII art / a step-by-step diagram, narrate what changes each step, then give time & space complexity with a one-line derivation. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
Catch bugs, edge cases, sub-optimality.
I'll paste my solution to **Maximum Length of Subarray With Positive Product**. Review it for correctness, missed edge cases, and time/space complexity, then coach me toward the optimal — don't just rewrite it. Ask me to paste my code now. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
Lock in recognition with look-alikes.
Give me 2 problems that use the SAME underlying pattern as **Maximum Length of Subarray With Positive Product**. For each, let me attempt first, then review my answer and name the trigger signal that reveals the pattern. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.