The Maximum Length of Subarray With Positive Product coding problem asks for the length of the longest contiguous subarray whose product of all elements is strictly positive. A product is positive when there are zero negatives or an even number of negatives in the subarray. Zeros reset everything. This elegant problem tests your understanding of product sign behavior in subarrays.
Arcesium and Amazon include this problem to test greedy reasoning over linear sequences with special "reset" elements (zeros). Candidates must understand that zeros break subarrays into independent segments and that within each segment, the product sign depends solely on the parity of negative numbers. Both greedy and DP solutions are valid, and interviewers often ask candidates to explain both.
Greedy: Within each zero-free segment, the product is positive for the full subarray if the count of negatives is even. If odd, either trim from the left (up to and including the first negative) or from the right (up to and including the last negative) — whichever leaves a longer subarray.
DP: Maintain pos = length of longest subarray ending here with positive product, neg = length with negative product. If nums[i] > 0: pos = pos+1, neg = neg+1 if neg>0 else 0. If nums[i] < 0: new pos = neg+1 if neg>0 else 0, new neg = pos+1. If nums[i] = 0: pos = neg = 0.
Array: [1, -2, -3, 4]
Array: [1, -2, 3, 0, -1, 4]
DP at each step:
DP: i=2(val=3>0): new_pos = pos+1 = 0+1=1, new_neg = neg+1 = 2+1=3. So pos=1, neg=3. Max=1. Then i=3(0): pos=neg=0. i=4(-1<0): pos=neg+1=1 if neg>0 else 0 = 1 (neg was 0+1=0, so pos=0). neg=pos+1=1+1=2. Hmm, this shows the DP details get subtle — exactly what interviewers probe.
For the Array Greedy Dynamic Programming interview pattern, the DP tracking (pos, neg) lengths is a clean O(n) solution. Practice the DP state transition on paper for arrays with zeros and multiple negatives. Knowing both greedy (segment + trim) and DP approaches lets you discuss trade-offs in the interview.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Best Time to Buy and Sell Stock with Transaction Fee | Medium | Solve | |
| Jump Game II | Medium | Solve | |
| Jump Game | Medium | Solve | |
| Best Time to Buy and Sell Stock II | Medium | Solve | |
| Check if it is Possible to Split Array | Medium | Solve |