Skip to the solution
MediumDSA10 min read

How do you find the maximum product subarray?

497 views

The problem

Question presented to candidate: "Given an integer array that can contain negative numbers and zeros, find the contiguous subarray with the largest product and return that product. Walk me through your idea, then code it in Python."

What a strong answer should cover:

  • Why plain Kadane (keep only the best product ending here) fails: a negative number turns the smallest product into the largest, so you must track both the maximum and the minimum product ending at each index.
  • The recurrence: at each x, the new max is the largest of x, max * x and min * x (and the new min is the smallest of the same three); a zero resets both to 0, and the running best is updated every step.
  • O(n) time and O(1) extra space, compared with the O(nΒ²) brute force that tries every start and end.
  • The alternative prefix/suffix scan (multiply left to right and right to left, restarting after a zero) and why it works: inside a stretch with no zero, the best product is always a prefix or a suffix of that stretch.
  • Python details: int has arbitrary precision so products never overflow (they just get bigger and slower), the tuple swap hi, lo = lo, hi, and that nums[1:] copies the list.

Clarifying questions expected:

  • Can the array contain zeros and negatives, and can it be empty?
  • Is the answer guaranteed to fit in a 32-bit (or 64-bit) integer?
  • Do you want just the product, or also the start and end indices of the subarray?

Code / implementation expected: Yes β€” a one-pass Python function that keeps the max and min product ending at each index.

  • dp
  • arrays

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

10 min read Β· 13 sections

Python code

Edit the code and run it here. Each printed line with an expected value becomes a test.

PythonMax product subarray: max/min tracking on edge cases, with a trace
PythonBrute force vs one pass vs prefix/suffix scan on random arrays

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 86 of 154 in DSA

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All DSA questions
Up nextMedium

How do you solve the house robber problem?

Continue