LeetCode 1567: Maximum Length of Subarray With Positive Product
LeetCode 1567 Solution Explanation
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.
LeetCode 1567 Solutions in Java, C++, Python
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;
}
}
Interactive Code Editor for LeetCode 1567
Improve Your LeetCode 1567 Solution
Use the editor below to refine the provided solution for LeetCode 1567. Select a programming language and try the following:
- Add import statements if required.
- Optimize the code for better time or space complexity.
- Add test cases to validate edge cases and common scenarios.
- Handle error conditions or invalid inputs gracefully.
- Experiment with alternative approaches to deepen your understanding.
Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.
Loading editor...