Maximum Product Subarray solution explained

Maximum Product Subarray asks for the largest product of any contiguous, non-empty run in an array of integers that may include negatives and zeros. Walk the array once while keeping two values, the largest and the smallest product of a run ending at the current index; a negative number turns the smallest into the largest, so you need both. That gives an O(n) time, O(1) space solution.

By Published 7 min read

The task, restated

You get a list of integers. Some are positive, some negative, some zero. Choose one unbroken stretch of the list, at least one element long, and multiply its elements together. Return the largest product you can get this way. The stretch has to be contiguous: you cannot skip the elements you dislike in the middle.

Examples made up for this page
ArrayLargest productStretch
[2, -5, -2, -4, 3]24-2, -4, 3
[3, -1, 4, 0, 5, 2]105, 2 (the 0 splits the array)
[-1, -2, -3]6-2, -3
[0, -1, 0]0Either 0
[-3]-3The only stretch there is
Examples made up for this page. Scroll sideways on a small screen.

Worth confirming: the stretch must be non-empty, so an array of one negative number returns that negative number, not 1 and not 0. Also ask about the size of values and the length, since products grow fast. Ask whether the answer is promised to fit a fixed-width integer; if not, Python is fine and JavaScript needs care past 2^53.

Why the sum trick is not enough

If you know Kadane's algorithm for the maximum subarray sum, you will try the same thing: keep the best product ending here, and either extend it or start fresh. That breaks on [2, -5, -2]. After 2 and -5, the best product ending at -5 is -5 itself, which looks useless, so you might forget it. Then -2 arrives and -5 × -2 = 10 turns out to be the best ending at -2. The run that was worst a moment ago became the best. So keep the smallest product ending here alongside the largest.

Brute force: fix a start, extend to the right

For each start index, multiply forward one element at a time and track the largest product seen. Reusing the running product avoids a third loop, so this is O(n²) time and O(1) space. It is correct, easy to write, and makes a good reference for testing.

def top_product_slow(nums):
    best = nums[0]
    for start in range(len(nums)):
        running = 1
        for end in range(start, len(nums)):
            running *= nums[end]
            best = max(best, running)
    return best
Every start, running product, O(n²).

Optimal approach: carry a high and a low

At each index, the largest product of a run ending here is one of three numbers: the element alone, the element times the previous high, or the element times the previous low. The smallest is one of the same three. Compute both from the old values before overwriting either, then update the overall best with the new high. Zeros need no special branch: the element alone is 0, the two products are 0, so both high and low reset to 0 and the next element starts fresh.

Trace for [2, -5, -2, -4, 3]
ElementHigh ending hereLow ending hereBest so far
2222
-5-5-102
-220-220
-48-8020
324-24024
Trace for [2, -5, -2, -4, 3]. Scroll sideways on a small screen.

Look at -4. The high of 20 times -4 is -80, which becomes the low, while the old low of -2 times -4 gives 8, which becomes the high. Then 3 multiplies the 8 into 24. Without the low, the 8 would never exist.

def top_product(nums):
    high = low = best = nums[0]
    for x in nums[1:]:
        candidates = (x, high * x, low * x)
        high, low = max(candidates), min(candidates)
        best = max(best, high)
    return best
Python: one pass, O(n) time, O(1) extra space.
function topProduct(nums) {
  let high = nums[0];
  let low = nums[0];
  let best = nums[0];
  for (let i = 1; i < nums.length; i++) {
    const x = nums[i];
    const a = high * x;
    const b = low * x;
    high = Math.max(x, a, b);
    low = Math.min(x, a, b);
    best = Math.max(best, high);
  }
  return best;
}
JavaScript: the same update with both products computed first.

In JavaScript, a negative times zero gives -0, a value that prints as 0. It can only show up in low, never in high, because the element itself is +0 and Math.max prefers +0 over -0. So the returned best is a plain 0 when the answer is zero. If you ever compare results with Object.is, keep that in mind.

Alternative: products from both ends

There is a neat second solution. Inside a zero-free stretch, the best product uses either everything (if the count of negatives is even) or everything except a prefix or a suffix that ends at the first or last negative. So a running product from the left and another from the right, each restarting after a zero, will pass through the answer. It is also O(n) and O(1), and some people find it easier to trust. The high-low version is the one most interviewers expect, but knowing both shows you understand why the answer is shaped the way it is.

def top_product_two_sweeps(nums):
    best = nums[0]
    left = right = 1
    n = len(nums)
    for i in range(n):
        left = (left or 1) * nums[i]
        right = (right or 1) * nums[n - 1 - i]
        best = max(best, left, right)
    return best
Python: prefix and suffix products, restarting after zeros.

The expression left or 1 restarts the product after it has become 0, which is how each zero splits the array into independent stretches.

Time and space

Cost for an array of n integers
VersionTimeExtra space
Every slice, product recomputedO(n³)O(1)
Every start, running productO(n²)O(1)
High and low ending hereO(n)O(1)
Prefix and suffix sweepsO(n)O(1)
Cost for an array of n integers. Scroll sideways on a small screen.

Edge cases

  • One element, negative: return it.
  • All negatives with an odd count, such as [-1, -2, -3]: drop one end, here the -1.
  • Zeros everywhere between negatives: the answer may be 0 itself when every stretch is a single negative.
  • A single zero next to one negative, as in [-4, 0]: the answer is 0.
  • Large values: products can overflow fixed-width integers quickly, so ask about bounds.

Mistakes to avoid

  • Tracking only the high, borrowed straight from the sum version.
  • Updating high first and then using the new high to compute low in the same step.
  • Starting best at 0 or 1 instead of the first element, which gives the wrong answer for [-3].
  • Writing special branches for zeros that reset state in the wrong order, when the three-candidate update already handles them.
  • Forgetting that the subarray must be contiguous and reaching for a subsequence answer.

How to explain it out loud

Fictional example

Explaining why two values are needed
Candidate
With sums, a bad prefix is never worth keeping. With products, a very negative run can become the best one when the next number is negative, so I cannot throw it away.
Candidate
At each index I keep the largest and smallest product ending there. The new ones come from three candidates: the number alone, times the old high, and times the old low.
Candidate
A zero makes all three candidates zero, which resets the run on its own. One pass, constant space. Let me trace 2, minus 5, minus 2 to show the low turning into the high.

Longest Palindromic Substring is another search over contiguous stretches, where expanding from a center replaces checking every slice. Coin Change builds a full table instead of rolling values. House Robber II also keeps two values per step, there the best totals one and two positions back.

Where Natively fits

Sign flips are where this problem goes wrong under pressure. In a practice round on Mac or Windows, Natively can capture the problem from your screen, suggest the high-and-low idea with Python or JavaScript to compare, and transcribe your explanation so you can check that you traced a negative case before claiming it works. See the AI interview assistant page for how it is set up.

Questions people ask

How do you solve Maximum Product Subarray in O(n)?

Walk the array once and keep the largest and smallest product of a run ending at the current index. The new values come from three candidates: the element alone, the element times the old high, and the element times the old low.

Why do you need the minimum product in Maximum Product Subarray?

Multiplying by a negative number swaps large and small. A very negative run can become the largest product one step later, so you must keep it.

How does Maximum Product Subarray handle zeros?

A zero makes all three candidates zero, so both running values reset and the next element starts a new run. No special branch is needed, and the answer can be 0 itself.

Is there another way to solve Maximum Product Subarray?

Yes. Keep a running product from the left and one from the right, each restarting after a zero, and track the largest value either one reaches. It is also O(n) time and O(1) space.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP