713586. Length of the longest subarray with positive product

Medium

Length of the longest subarray with positive product

Summary

Given an array of integers, find the length of the longest subarray where the product of all elements is positive. This problem requires a dynamic programming approach to solve.

Detailed Explanation

The idea behind this solution is to use a dynamic programming approach where we maintain two arrays: one for maximum and another for minimum product ending at each position. We start by initializing these arrays with 1, since the product of an empty subarray is 1 (by convention). Then, we iterate through the array from left to right, updating our arrays based on the current element.

Here's a step-by-step breakdown:

  • Initialize two arrays max_product and min_product of size n, where n is the length of the input array. Set all elements to 1.
  • Iterate through the array from left to right:
    • For each element arr[i], calculate the maximum product ending at i by taking the maximum of:
      • The current maximum product (max_product[i-1]) multiplied by arr[i].
      • The minimum product ending at i-1 (if it's positive) multiplied by arr[i]. If the minimum product is negative, we can't extend the subarray with a positive product.
    • Calculate the minimum product ending at i in a similar manner:
      • The current minimum product (min_product[i-1]) divided by arr[i], if it's positive. If the division would result in a negative number, we set it to 1 (since the product of an empty subarray is 1).
    • Update max_product and min_product arrays with the calculated values.
  • The length of the longest subarray with a positive product is the maximum value in the max_product array.

Time complexity: O(n) Space complexity: O(n)

Optimized Solutions

Here are optimized solutions in various languages:

Java

View on GeeksforGeeks
public int longestSubarray(int[] arr) {
    int n = arr.length;
    int[] maxProduct = new int[n];
    int[] minProduct = new int[n];

    maxProduct[0] = 1;
    minProduct[0] = 1;

    for (int i = 1; i < n; i++) {
        if (arr[i] > 0) {
            maxProduct[i] = Math.max(maxProduct[i-1] * arr[i], minProduct[i-1] * arr[i]);
            minProduct[i] = Math.min(minProduct[i-1] / arr[i], 1);
        } else {
            maxProduct[i] = 1;
            minProduct[i] = 1;
        }
    }

    int maxLength = 0;
    for (int i = 0; i < n; i++) {
        if (maxProduct[i] > 0) {
            maxLength = Math.max(maxLength, i + 1);
        }
    }

    return maxLength;
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.