LeetCode 1567: Maximum Length of Subarray With Positive Product
Problem Description
Explanation
To solve this problem, we can iterate through the array while keeping track of the running product and the indices of the first positive and negative numbers encountered so far. We can use a hashmap to store the indices of the running product values. If the running product is positive, we can calculate the length of the subarray by subtracting the current index from the index of the first positive number. If the running product is negative, we can calculate the length of the subarray by subtracting the current index from the index of the first negative number. We update the maximum length of the positive product subarray as we iterate through the array.
Algorithm:
- Initialize variables
maxLen
to store the maximum length of subarray with positive product,posIndex
andnegIndex
to store the indices of the first positive and negative numbers encountered, and a hashmapproductIndex
to store the running product values. - Iterate through the array
nums
and calculate the running product. - If the running product is positive, calculate the length of the subarray using
i - posIndex
. - If the running product is negative, calculate the length of the subarray using
i - negIndex
. - Update the
maxLen
if necessary. - Update the
productIndex
hashmap with the running product and its index. - Return the
maxLen
.
Time Complexity: O(N) where N is the number of elements in the array. Space Complexity: O(N) for the hashmap to store running product values.
Solutions
class Solution {
public int getMaxLen(int[] nums) {
int maxLen = 0;
int posIndex = -1, negIndex = -1;
Map<Integer, Integer> productIndex = new HashMap<>();
productIndex.put(1, -1);
int product = 1;
for (int i = 0; i < nums.length; i++) {
product *= nums[i];
if (productIndex.containsKey(product)) {
maxLen = Math.max(maxLen, i - productIndex.get(product));
} else {
productIndex.put(product, i);
}
if (product > 0) {
maxLen = Math.max(maxLen, i - posIndex);
} else if (product < 0) {
maxLen = Math.max(maxLen, i - negIndex);
} else {
posIndex = i;
negIndex = i;
}
}
return maxLen;
}
}
Loading editor...