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_productandmin_productof sizen, wherenis 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 atiby taking the maximum of:- The current maximum product (
max_product[i-1]) multiplied byarr[i]. - The minimum product ending at
i-1(if it's positive) multiplied byarr[i]. If the minimum product is negative, we can't extend the subarray with a positive product.
- The current maximum product (
- Calculate the minimum product ending at
iin a similar manner:- The current minimum product (
min_product[i-1]) divided byarr[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).
- The current minimum product (
- Update
max_productandmin_productarrays with the calculated values.
- For each element
- The length of the longest subarray with a positive product is the maximum value in the
max_productarray.
Time complexity: O(n) Space complexity: O(n)
Optimized Solutions
Here are optimized solutions in various languages:
Java
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;
}