Maximum Product Subarray
Difficulty: Medium · Pattern: 1-D Dynamic Programming · LeetCode #152
Return the largest product of a contiguous non-empty subarray.
Examples
text
[2,3,-2,4] → 6
[-2,0,-1] → 0
[-2,3,-4] → 24Hints
- Kadane's algorithm for sums keeps the best sum ending at i. Why isn't that enough for products?
- Multiplying by a negative number turns the smallest (most negative) product into the largest. Track both.
Approach
Keep hi and lo, the maximum and minimum product of a subarray ending at i:
text
for x in nums[1:]:
candidates = (x, hi*x, lo*x)
hi, lo = max(candidates), min(candidates)
best = max(best, hi)Including x alone lets a zero "reset" the run. If x < 0, the roles of hi and lo swap automatically because both products are among the candidates. O(n) time, O(1) space.
Complexity
Time: O(n). Space: O(1).
Python solution
def maxProduct(nums):
hi = lo = best = nums[0]
for x in nums[1:]:
cands = (x, hi * x, lo * x)
hi, lo = max(cands), min(cands)
best = max(best, hi)
return bestJavaScript solution
function maxProduct(nums) {
let hi = nums[0], lo = nums[0], best = nums[0];
for (let i = 1; i < nums.length; i++) {
const x = nums[i], a = hi * x, b = lo * x;
hi = Math.max(x, a, b); lo = Math.min(x, a, b);
best = Math.max(best, hi);
}
return best;
}