Skip to content

Maximum Product Subarray

Find the largest product of a contiguous subarray by tracking the biggest and smallest products so far.

Medium1D Dynamic Programming
Solve on LeetCode

The problem

You get an integer array nums that can hold negative numbers and zeros. Return the largest product of any non-empty contiguous subarray. You can assume every such product fits in a 32-bit integer.

Input nums = [-3, 4, -2, 0, 5]

Output 24

(-3) * 4 * (-2) = 24: the two negatives cancel out.

Input nums = [-4, 0, -1, -3]

Output 3

(-1) * (-3) = 3. Any subarray that crosses the 0 has product 0.

Key constraint: The array can hold 20,000 numbers, so checking every subarray, about 200 million of them, is too slow.

How to spot the pattern

  • You want the best contiguous subarray, as in Maximum Subarray, but with products.
  • Negative numbers flip signs, so the worst product so far can become the best one after one more number.
  • Zeros cut the array into independent pieces.

The idea

For sums you only track the best subarray ending here, but with products a very negative value times a negative number becomes very positive. So keep two states for the subarray ending at index i: hi, its largest product, and lo, its smallest. With x = nums[i], both come from the three candidates x, hi * x and lo * x, and the answer is the largest hi ever seen.

Brute force: Multiply out every subarray with two nested loops, which takes O(n^2) time.

Step by step

  1. 1Start hi, lo and best at nums[0].
  2. 2For each next number x, form the candidates x (start fresh), hi * x and lo * x.
  3. 3Set hi to the largest candidate and lo to the smallest, computing both from the old values.
  4. 4Update best with hi, and return best at the end.

See the pattern move

The 1d dynamic programming pattern on a small example. Step through it, or press play.

Code

class Solution:
    def maxProduct(self, nums: List[int]) -> int:
        # hi and lo: largest and smallest product of a subarray ending at the current number
        hi = lo = best = nums[0]
        for x in nums[1:]:
            # start fresh at x, or extend the best or the worst run;
            # a negative x turns the smallest product into the largest
            candidates = (x, hi * x, lo * x)
            hi, lo = max(candidates), min(candidates)
            best = max(best, hi)
        return best

Complexity

Time

O(n)

Space

O(1)

One pass that keeps three numbers.

Watch out for

  • Tracking only the largest product: a negative number can turn the smallest product into the largest.
  • Updating hi first and then using the new hi to compute lo; both must come from the old values.
  • Starting best at 0: for [-5] the answer is -5.

Follow-up questions

Is there another way to see it?

Between two zeros, the best product is always a prefix or a suffix of that stretch, because only the count of negatives matters. So scanning running products from the left and from the right, restarting after each 0, gives the same answer.

In Hinglish

Negative number aate hi sabse chhota product sabse bada ban sakta hai, isliye `hi` aur `lo` dono saath leke chalo.

Related problems