Maximum Product Subarray

MediumKadane’s Algorithm · Max/Min DP🧩 Kadane's Running BestLeetCode #152 ↗Updated

Problem

Given an integer array nums containing positives, negatives and zeros, find the non-empty contiguous block whose elements multiply to the largest product, and return that product.
Input[2,3,-2,4]Output6 ([2,3])
Input[-2,0,-1]Output0
Input[-2,3,-4]Output24

1 ≤ n ≤ 2·104  ·  -10 ≤ nums[i] ≤ 10  ·  every subarray product fits in a 32-bit int

Try it yourself

Java
class Solution {
    public int maxProduct(int[] nums) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
A negative number turns the smallest product into the largest. So track both the max and the min product ending at each index; a zero simply resets both.
PatternKadane's Running Best

Instinct Best sum or product of a contiguous subarray in one pass? At each index choose - extend the run ending here or restart - and track the global best.

Memory hack Carry the bag only while it helps - a negative past is dead weight, drop it and restart here.

Open the Kadane's Running Best guide →

Approaches

Brute ForceAll Subarrays, Running Product

Time O(n2)Space O(1)

Fix each start i, extend j and multiply a running product by nums[j], so each subarray is evaluated in O(1). Keep the largest product seen.

Java
public int maxProduct(int[] nums) {
    int maxProduct = Integer.MIN_VALUE;
    for (int i = 0; i < nums.length; i++) {
        int product = 1;
        for (int j = i; j < nums.length; j++) {
            product *= nums[j]; // product of nums[i..j]
            maxProduct = Math.max(maxProduct, product);
        }
    }
    return maxProduct;
}

Straightforward, but quadratic — too slow for n = 2·104 in many judges.

At a glance

LevelApproachTimeSpace
Brute ForceAll Subarrays, Running ProductO(n2)O(1)
BetterDP Tables (max & min ending here)O(n)O(n)
OptimalRolling Max/Min (Kadane Variant)O(n)O(1)
Common pitfalls
  • Tracking only the max (plain Kadane) — [-2,3,-4] gives 3 instead of 24.
  • Updating max then using the new max to compute min — save it first or swap.
  • Initialising best = 0 — wrong for [-3].
Interview tips
  • Start from Maximum Subarray, then show the counter-example that breaks plain Kadane.
  • Explain zeros: they make both max and min collapse to x, i.e. a restart.
  • Mention overflow: use long/double if products are not guaranteed to fit.
Pattern
Kadane with dual state (max & min) → contiguous optimum where a sign flip can swap best and worst.
My notes saved in this browser