Maximum Product Subarray
Find the largest product of a contiguous subarray by tracking the biggest and smallest products so far.
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
- 1Start
hi,loandbestatnums[0]. - 2For each next number
x, form the candidatesx(start fresh),hi * xandlo * x. - 3Set
hito the largest candidate andloto the smallest, computing both from the old values. - 4Update
bestwithhi, and returnbestat 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 bestComplexity
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
hifirst and then using the newhito computelo; both must come from the old values. - Starting
bestat 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.