Maximum Product Subarray
Pattern: Kadane and subarray sums
Track both the largest and the smallest product of a block ending here. A negative value swaps their roles, so the most negative product can become the best one.
The problem
Given an array of whole numbers, return the largest product of a non-empty block of neighbouring elements. For example,
[2, 3, -2, 4] gives 6 (2 × 3), [-2, 0, -1] gives 0, and [-2, 3, -4] gives 24.
The function name maxProduct matches LeetCode, which promises the answer fits in 32 bits. Use the link above for the
exact statement and limits.
Think first
- Plain Kadane keeps the best product ending here. Find an input where that fails.
- After multiplying by a negative number, which earlier product becomes the largest?
- What does a 0 do to every block that contains it?
Hints
Brute force, and why it fails
Multiply out every block with a running product: O(n²). Tracking both ends is O(n).
The key insight
Multiplying by a negative number flips the order of products, so the best product ending here comes from either the best or the worst one before it. Keeping both makes one pass enough.
Dry run
| high | -2 |
|---|---|
| low | -2 |
| best | -2 |
nums = [-2, 3, -4]. high and low are the largest and smallest products of a block ending here. Both start at -2.
The plan
high = low = best = nums[0]
for i from 1 to n - 1:
v = nums[i]
if v < 0: swap high and low
high = max(v, high × v)
low = min(v, low × v)
best = max(best, high)
return best
Complexity
- Time
O(n)- Space
O(1)
One pass with three numbers.
Edge cases
- A single negative value: that value, as in
[-2]. - Zeros:
highandlowrestart from the next value, sincemax(v, 0)takes over. - An even number of negatives across the whole array: the whole array, if it has no zeros.
I've built my logic, show the code
Java
class Solution {
public int maxProduct(int[] nums) {
int best = nums[0];
int high = nums[0]; // largest product of a subarray ending here
int low = nums[0]; // smallest (most negative) product ending here
for (int i = 1; i < nums.length; i++) {
int v = nums[i];
if (v < 0) { // a negative number turns the smallest into the largest
int temp = high;
high = low;
low = temp;
}
high = Math.max(v, high * v);
low = Math.min(v, low * v);
best = Math.max(best, high);
}
return best;
}
}C++
class Solution {
public:
int maxProduct(vector<int>& nums) {
int best = nums[0];
int high = nums[0]; // largest product of a subarray ending here
int low = nums[0]; // smallest (most negative) product ending here
for (int i = 1; i < static_cast<int>(nums.size()); i++) {
int v = nums[i];
if (v < 0) swap(high, low); // a negative number turns the smallest into the largest
high = max(v, high * v);
low = min(v, low * v);
best = max(best, high);
}
return best;
}
};Python
class Solution:
def maxProduct(self, nums: list[int]) -> int:
best = high = low = nums[0] # high / low: largest and smallest product ending here
for v in nums[1:]:
if v < 0:
high, low = low, high # a negative number turns the smallest into the largest
high = max(v, high * v)
low = min(v, low * v)
best = max(best, high)
return bestCommon mistakes
- Keeping only the largest product, which fails on
[-2, 3, -4]. - Updating
highfirst and then using the newhighto computelow. Swap before, or save the old value. - Starting
bestat 0 or 1 instead ofnums[0].