Program to find maximum length of subarray with positive product in Python

When working with arrays containing positive and negative numbers, we often need to find the maximum length of a subarray where the product of all elements is positive. A product is positive when there's an even number of negative values in the subarray.

So, if the input is like nums = [2,-2,-4,5,-3], then the output will be 4 because the first four elements [2,-2,-4,5] form a subarray with product 2×(-2)×(-4)×5 = 80, which is positive.

Algorithm Approach

To solve this problem, we need to ?

  • Split the array by zeros (since zero makes any product zero)
  • For each non-zero segment, count negative numbers
  • If negative count is even, the entire segment has positive product
  • If negative count is odd, exclude either the first or last negative number

Implementation

def util(nums, start, end):
    """Helper function to find max length in a segment without zeros"""
    neg_count = 0
    first_neg = -1
    last_neg = -1
    
    # Count negatives and track positions
    for i in range(start, end + 1):
        if nums[i] < 0:
            neg_count += 1
            if first_neg == -1:
                first_neg = i
            last_neg = i
    
    # If even negatives (or zero), entire segment works
    if neg_count % 2 == 0:
        return end - start + 1
    else:
        # Remove either first or last negative
        return max(end - first_neg, last_neg - start)

def solve(nums):
    """Find maximum length subarray with positive product"""
    max_length = 0
    start = -1
    
    for i in range(len(nums)):
        if nums[i] != 0 and start == -1:
            # Start of new non-zero segment
            start = i
        elif nums[i] == 0 and start != -1:
            # End of current segment
            end = i - 1
            max_length = max(max_length, util(nums, start, end))
            start = -1
    
    # Handle last segment if it doesn't end with zero
    if start != -1:
        end = len(nums) - 1
        max_length = max(max_length, util(nums, start, end))
    
    return max_length

# Test the function
nums = [2, -2, -4, 5, -3]
result = solve(nums)
print(f"Maximum length of subarray with positive product: {result}")
Maximum length of subarray with positive product: 4

How It Works

Let's trace through the example [2, -2, -4, 5, -3] ?

def trace_example():
    nums = [2, -2, -4, 5, -3]
    print(f"Input array: {nums}")
    
    # No zeros, so entire array is one segment
    print("Segment: indices 0 to 4")
    
    # Count negatives: -2, -4, -3 = 3 negatives (odd)
    neg_positions = [1, 2, 4]  # positions of negatives
    print(f"Negative numbers at positions: {neg_positions}")
    print(f"Count of negatives: {len(neg_positions)} (odd)")
    
    # Since odd negatives, try removing first or last
    first_neg = 1
    last_neg = 4
    
    option1 = 4 - first_neg  # exclude first negative: [_,-4,5,-3]
    option2 = last_neg - 0   # exclude last negative: [2,-2,-4,5,_]
    
    print(f"Option 1 - exclude first negative: length = {option1}")
    print(f"Option 2 - exclude last negative: length = {option2}")
    print(f"Maximum: {max(option1, option2)}")

trace_example()
Input array: [2, -2, -4, 5, -3]
Segment: indices 0 to 4
Negative numbers at positions: [1, 2, 4]
Count of negatives: 3 (odd)
Option 1 - exclude first negative: length = 3
Option 2 - exclude last negative: length = 4
Maximum: 4

Additional Examples

# Test with different cases
test_cases = [
    [1, -2, -3, 4],      # Even negatives
    [0, 1, -2, -3, 0, 4], # With zeros
    [-1, -2, -3, -4],     # All negatives (even count)
    [1, 2, 3]            # All positives
]

for i, nums in enumerate(test_cases, 1):
    result = solve(nums)
    print(f"Test case {i}: {nums}")
    print(f"Max length: {result}\n")
Test case 1: [1, -2, -3, 4]
Max length: 4

Test case 2: [0, 1, -2, -3, 0, 4]
Max length: 3

Test case 3: [-1, -2, -3, -4]
Max length: 4

Test case 4: [1, 2, 3]
Max length: 3

Conclusion

This algorithm efficiently finds the maximum length subarray with positive product by splitting on zeros and handling negative counts in each segment. The time complexity is O(n) and space complexity is O(1).

Updated on: 2026-03-26T13:44:47+05:30

329 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements