← Whiteboard questions

Maximum Product Subarray

Find the contiguous subarray with the largest product

DSA, Medium, 1-D DP

Which structure or algorithm, and what does it cost.

A list nums holds whole numbers, and some may be negative or zero. A run is a non-empty stretch of neighbouring values. Its product is all of its values multiplied together. Return the largest product that any run has.

Examples

Input nums = [2, -3, 4, -1, 5]
Output 120
Why the whole list: the two negative values cancel, and 2 x -3 x 4 x -1 x 5 = 120.
Input nums = [3, -2, 0, 4, -1, -2]
Output 8
Why the run 4, -1, -2 gives 8. Any run that holds the 0 gives 0.
Input nums = [-6]
Output -6
Why edge case: the only run is the one value, so the answer can be negative.

Constraints

Your answer must contain

Target Aim for O(n) time and O(1) memory.

Hints

Try the problem first. Open one hint at a time.

Hint 1 a nudge

What does a negative value do to a running product? What if the product so far was already negative?

Hint 2 the approach

For each position, track something about the runs that end there, then update it when the next value arrives.

Hint 3 the key step

Keep both the largest and the smallest product of a run ending here. The next pair comes from the new value alone, or the new value times either old product.

Walkthrough

Full walkthrough brute force to best

Brute force

Try every start, extend the end one value at a time while carrying the product, and keep the largest. There are about n^2 / 2 runs: 5,000,050,000 for n = 100,000. That is too slow.

Better method

Another O(n) way: prefix and suffix products. Split the list at zeros. In a stretch with no zero, a positive total product is the best run. A negative total means the best run drops everything up to the first negative from the left, or from the last negative to the right. So the best run is always a prefix or a suffix of a stretch between zeros. Scan from the left and from the right, multiply as you go, and restart at 1 after a zero. This is O(n) time and O(1) memory.

Best method

Walk along the list and keep, for runs that end at the current value, the largest product hi and the smallest product lo. A new run ending at the next value x is either x alone or an older run extended by x. A positive x keeps the order of hi and lo and a negative x swaps it, so the largest and smallest new products come from x, hi times x or lo times x. This is why lo matters: a very negative product times a negative x becomes a large positive one. A zero gives hi = lo = 0, and the next value starts fresh because x alone is one of the options. Both new values are computed from the old pair. Track the best hi seen. Starting from the first value, not from 0, keeps an all-negative list correct.

Hand trace

Run on [2, -3, 4, -1, 5]. Start with hi = 2, lo = 2 and best = 2. Value -3: the options are -3, 2 x -3 = -6 and 2 x -3 = -6, so hi = -3 and lo = -6. Value 4: the options are 4, -3 x 4 = -12 and -6 x 4 = -24, so hi = 4 and lo = -24. Value -1: the options are -1, 4 x -1 = -4 and -24 x -1 = 24, so hi = 24 and lo = -4. Value 5: the options are 5, 24 x 5 = 120 and -4 x 5 = -20, so hi = 120 and lo = -20. The best seen is 120.

Code

def max_product(nums):
    best = hi = lo = nums[0]        # best so far, and the largest and smallest product of a run ending here
    for x in nums[1:]:
        hi, lo = max(x, hi * x, lo * x), min(x, hi * x, lo * x)
        best = max(best, hi)
    return best

Time and memory

O(n) time, because each value is handled once. O(1) memory, because only three numbers are kept.

Common mistakes

  • Keeping only the largest product ending here. A big negative product can become the answer after the next negative value. On [2, -3, 4, -1, 5] that gives 5, not 120.
  • Starting the best at 0. An all-negative list such as [-6] must answer -6, so start from the first value.
  • Updating hi first and then using the new hi to compute lo. Both values must come from the old pair.

Related problems

More 1-D DP problems
Maximum Product Subarray: walkthrough and Python solution