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:

  1. Initialize variables maxLen to store the maximum length of subarray with positive product, posIndex and negIndex to store the indices of the first positive and negative numbers encountered, and a hashmap productIndex to store the running product values.
  2. Iterate through the array nums and calculate the running product.
  3. If the running product is positive, calculate the length of the subarray using i - posIndex.
  4. If the running product is negative, calculate the length of the subarray using i - negIndex.
  5. Update the maxLen if necessary.
  6. Update the productIndex hashmap with the running product and its index.
  7. 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...