Browse curriculum

Maximum Product Subarray (LeetCode 152)

Maximum Product Subarray (LeetCode 152): find the largest product of a contiguous subarray in one pass by tracking both the largest and the smallest running product.

Problem Understanding

Maximum Product Subarray: given an integer array nums, return the largest product of any contiguous, non-empty subarray.

Example: nums = [2, 3, -2, 4] returns 6, from the subarray [2, 3]. nums = [-2, 0, -1] returns 0.

Attempt 1: Every Subarray

Fix a start index, extend the end one step at a time and multiply as you go, keeping the largest product. That is O(n²) time. The waste is that every start index recomputes products the previous one already formed.

The Intuition: Two Running Products

For a maximum sum, Kadane's algorithm keeps the best sum ending at the current index. Products need one more value, because a negative number turns the smallest product into the largest.

Keep, for the subarray ending at the current index:

  • curMax, the largest product, and
  • curMin, the smallest (most negative) product.

For each new x: if it is negative, swap the two. Then either extend or start fresh at x: curMax = max(x, curMax * x) and curMin = min(x, curMin * x). The answer is the largest curMax seen.

Maximum Product Subarray Visualization

START

nums

i

2

0

3

1

-2

2

4

3

curMax

2

curMin

2

best

2

 

Start at nums[0] = 2: best = curMax = curMin = 2

Next

x = nums[1] = 3

Free preview: the first 3 of 9 steps

Array

The pointer moves one number at a time while curMax, curMin and best update beside the array. On a negative number, watch the swap step: the smallest product is about to become the largest.

Maximum Product Subarray Dry Run

Input: nums = [2, 3, -2, 4]

x Swap? curMax curMin best
2 (start) - 2 2 2
3 no 6 3 6
-2 yes -2 -12 6
4 no 4 -48 6

The answer is 6, from [2, 3]. At -2 the products 6 and 3 swap places before the multiply, giving curMin = -12; a later negative would turn that into a large positive product.

Maximum Product Subarray LeetCode Solution

One pass with the largest and smallest product ending at each index.

Maximum Product Subarray Code
1var maxProduct = function(nums) {
2 let best = nums[0], curMax = nums[0], curMin = nums[0];
3 for (let i = 1; i < nums.length; i++) {
4 const x = nums[i];
5 if (x < 0) {
6 [curMax, curMin] = [curMin, curMax];
7 }
8 curMax = Math.max(x, curMax * x);
9 curMin = Math.min(x, curMin * x);
10 best = Math.max(best, curMax);
11 }
12 return best;
13};

Maximum Product Subarray in Python, Java, C++, TypeScript and C

Maximum Product Subarray in Python
class Solution:
    def maxProduct(self, nums: List[int]) -> int:
        best = cur_max = cur_min = nums[0]
        for x in nums[1:]:
            if x < 0:
                cur_max, cur_min = cur_min, cur_max
            cur_max = max(x, cur_max * x)
            cur_min = min(x, cur_min * x)
            best = max(best, cur_max)
        return best
Maximum Product Subarray in Java
class Solution {
    public int maxProduct(int[] nums) {
        int best = nums[0], curMax = nums[0], curMin = nums[0];
        for (int i = 1; i < nums.length; i++) {
            int x = nums[i];
            if (x < 0) {
                int tmp = curMax; curMax = curMin; curMin = tmp;
            }
            curMax = Math.max(x, curMax * x);
            curMin = Math.min(x, curMin * x);
            best = Math.max(best, curMax);
        }
        return best;
    }
}
Maximum Product Subarray in C++
class Solution {
public:
    int maxProduct(vector<int>& nums) {
        int best = nums[0], curMax = nums[0], curMin = nums[0];
        for (int i = 1; i < (int)nums.size(); i++) {
            int x = nums[i];
            if (x < 0) {
                swap(curMax, curMin);
            }
            curMax = max(x, curMax * x);
            curMin = min(x, curMin * x);
            best = max(best, curMax);
        }
        return best;
    }
};
Maximum Product Subarray in TypeScript
function maxProduct(nums: number[]): number {
    let best = nums[0], curMax = nums[0], curMin = nums[0];
    for (let i = 1; i < nums.length; i++) {
        const x = nums[i];
        if (x < 0) {
            [curMax, curMin] = [curMin, curMax];
        }
        curMax = Math.max(x, curMax * x);
        curMin = Math.min(x, curMin * x);
        best = Math.max(best, curMax);
    }
    return best;
}
Maximum Product Subarray in C
int maxProduct(int* nums, int numsSize) {
    int best = nums[0], curMax = nums[0], curMin = nums[0];
    for (int i = 1; i < numsSize; i++) {
        int x = nums[i];
        if (x < 0) {
            int tmp = curMax; curMax = curMin; curMin = tmp;
        }
        curMax = x > curMax * x ? x : curMax * x;
        curMin = x < curMin * x ? x : curMin * x;
        if (curMax > best) best = curMax;
    }
    return best;
}

Edge Cases & Common Mistakes

  • Single element: the loop never runs; the answer is nums[0], even if it is negative.
  • Zeros: both products become 0 and the next number starts fresh, so subarrays never span a zero unless the answer is 0 itself.
  • Only tracking the maximum: [-2, 3, -4] would return 3 instead of 24.
  • The no-swap version: curMax = max(x, curMax * x, curMin * x) and curMin = min(x, curMax * x, curMin * x) also works, but only if the second line uses the old curMax. Save it before overwriting.

Summary

Maximum Product Subarray is Kadane's algorithm with two running values instead of one: the largest and smallest product ending at each index, swapped whenever a negative number arrives. One pass, O(1) extra space.

More practice: DSA interview questions with answers · patterns cheat sheet

The approach, step by step

  1. Start at the first element

    Set best, curMax and curMin to nums[0].

  2. Swap on a negative

    For each later x, if x is negative swap curMax and curMin.

  3. Extend or restart

    Set curMax = max(x, curMax * x), curMin = min(x, curMin * x), and best = max(best, curMax).

Frequently asked questions

Why track the minimum product as well as the maximum in Maximum Product Subarray?

Multiplying by a negative number flips signs: the smallest (most negative) product so far becomes the largest positive product. Tracking curMin ensures that a subsequent negative number can produce the global maximum.


Why can't Kadane's algorithm for maximum sum be used directly for products?

Kadane's algorithm tracks a single running sum because addition preserves ordering. Multiplication by a negative number reverses inequalities (-5 < 2, but -5 * -3 > 2 * -3), so the product variant must track both running maximum and minimum.


How does a zero element affect Maximum Product Subarray?

A zero resets running products to 0. The next element x starts fresh because max(x, 0 * x) = x when x is positive. Zero is also a valid candidate answer when all non-empty subarrays are negative.


What is the time and space complexity of Maximum Product Subarray?

Time complexity is O(n) for a single linear scan of the array. Space complexity is O(1) auxiliary space because only curMax, curMin, and best variables are maintained.

New to the technique behind this problem? Watch it run step by step:

Dynamic Programming Visualization

Applying for software engineering roles? Free, no sign-up:

AI resume checker: match your resume to the job description