Maximum Product Subarray
Given an integer array nums, find a contiguous non-empty subarray that has the largest product, and return the product.
- 1 <= nums.length <= 2 × 10⁴
- -10 <= nums[i] <= 10
- The product of any subarray of nums is guaranteed to fit in a 32-bit integer
nums = [2,3,-2,4]6nums = [-2,0,-1]0nums = [-2,3,-4]24nums = [-2]-2Finding the maximum product subarray means identifying a contiguous sequence of numbers that, when multiplied together, yield the largest possible value. Unlike summation, products are highly sensitive to zeros and negative numbers, which can instantly flip a result from very small to very large.
The simplest approach is to calculate the product of every possible subarray. We use two loops to define the window and keep a running product for each start point.
res = nums[0]
for i in range(len(nums)):
current_prod = 1
for j in range(i, len(nums)):
current_prod *= nums[j]
res = max(res, current_prod)
return resWe might try to apply basic Kadane's Algorithm (which works for sums). However, products are different because negative numbers flip results. In a sum, a huge negative number is always bad. In a product, a huge negative number is a "potential maximum" because multiplying it by another negative number could instantly make it the largest value in the array. This means tracking only the "best so far" is not enough.
Instead of checking all windows, we walk through the array exactly once while tracking two values: the current maximum AND the current minimum.
- When we hit a negative number, the max and min swap roles.
- This ensures we never "lose" a large negative buffer that could become our new maximum later.
max_p = min_p = result = nums[0]
for i in range(1, len(nums)):
num = nums[i]
if num < 0:
max_p, min_p = min_p, max_p # Roles swap
max_p = max(num, num * max_p)
min_p = min(num, num * min_p)
result = max(result, max_p)
return resultThe Sign Flipper
INSIGHT
Negatives are risky but valuable. They can turn the worst min into the best max instantly.
EFFICIENCY
We find the record in one single pass by keeping track of both extremes at every step.