DSA arrays and hashing learning path Level 3 This level · 1 of 2
Medium dsa arrays

Maximum Product Subarray

The 30 second answer

It looks like Kadane, but a negative number can turn the smallest product into the largest. So at each element I track both the maximum and the minimum product ending here. The new max is the largest of the element, element times old max and element times old min, and symmetrically for the min. One pass, constant space.

Could you say this in an interview?

Problem Return the largest product of any non-empty contiguous subarray. Original: LeetCode 152: Maximum Product Subarray.

Understanding the prompt "Contiguous subarray" means no gaps. Zeros reset a product, and an even count of negatives makes it positive.

Pattern recognition "Best contiguous subarray" points to Kadane. Multiplication by negatives forces you to also carry the minimum.

Brute force Try all subarrays while keeping a running product: O(n²).

Optimal Keep maxEnd and minEnd. For each x, take the max and min of {x, x·maxEnd, x·minEnd}, computing both from the old values.

Alternatives Prefix and suffix scan: the answer is the maximum running product from the left or from the right, resetting to 1 after a zero.

Java solution

public class MaxProductSubarray {
    static int maxProduct(int[] nums) {
        int maxEnd = nums[0], minEnd = nums[0], best = nums[0];
        for (int i = 1; i < nums.length; i++) {
            int x = nums[i];
            int a = x * maxEnd, b = x * minEnd;
            maxEnd = Math.max(x, Math.max(a, b));
            minEnd = Math.min(x, Math.min(a, b));
            best = Math.max(best, maxEnd);
        }
        return best;
    }

    public static void main(String[] args) {
        System.out.println(maxProduct(new int[] {2, 3, -2, 4}));  // 6
        System.out.println(maxProduct(new int[] {-2, 0, -1}));    // 0
        System.out.println(maxProduct(new int[] {-2, 3, -4}));    // 24
    }
}

Complexity O(n) time and O(1) space.

Edge cases

  • A single negative element returns that element.
  • Zeros split the array.
  • Two negatives make the whole run positive.

Follow-ups

  • Return the subarray's boundaries.
  • Possible overflow: ask whether the problem guarantees the product fits, which the original does. Otherwise use long or BigInteger.

Tests [2,3,-2,4] returns 6. [-2,0,-1] returns 0. [-2,3,-4] returns 24.

How to say it in the interview "Kadane alone fails because a negative flips min and max. So I keep both the max and the min product ending at each index, and update them from the previous pair. Linear time, constant space."

Sources (2)
  1. LeetCode 152: Maximum Product Subarrayleetcode.com
  2. Java SE 17 API: Mathdocs.oracle.com
Previous
Next