Maximum product subarray
Largest product of a contiguous run of numbers. A negative value can turn the smallest product into the largest.
Watch it animatedStep through it, with the running line highlighted. Free, no sign-in needed to watch.The idea
Unlike a sum, a product can flip sign. So track both the best (most positive) and worst (most negative) product ending at each index. A negative number swaps their roles, because multiplying the most negative value by another negative gives the new most positive one.
Code
public static int MaxProduct(int[] a) {
int maxEnd = a[0], minEnd = a[0], best = a[0];
for (int i = 1; i < a.Length; i++) {
if (a[i] < 0) (maxEnd, minEnd) = (minEnd, maxEnd);
maxEnd = Math.Max(a[i], maxEnd * a[i]);
minEnd = Math.Min(a[i], minEnd * a[i]);
best = Math.Max(best, maxEnd);
}
return best;
}static int maxProduct(int[] a) {
int maxEnd = a[0], minEnd = a[0], best = a[0];
for (int i = 1; i < a.length; i++) {
if (a[i] < 0) { int t = maxEnd; maxEnd = minEnd; minEnd = t; }
maxEnd = Math.max(a[i], maxEnd * a[i]);
minEnd = Math.min(a[i], minEnd * a[i]);
best = Math.max(best, maxEnd);
}
return best;
}int maxProduct(const vector<int>& a) {
int maxEnd = a[0], minEnd = a[0], best = a[0];
for (int i = 1; i < (int)a.size(); i++) {
if (a[i] < 0) swap(maxEnd, minEnd);
maxEnd = max(a[i], maxEnd * a[i]);
minEnd = min(a[i], minEnd * a[i]);
best = max(best, maxEnd);
}
return best;
}def max_product(a: list[int]) -> int:
max_end = min_end = best = a[0]
for x in a[1:]:
if x < 0: max_end, min_end = min_end, max_end
max_end = max(x, max_end * x)
min_end = min(x, min_end * x)
best = max(best, max_end)
return bestTips
- Keep both a running max and a running min ending at the current index, not just one.
- If any element is 0, both running values reset to 0 there, since no product can cross a zero.
In the .NET library
Forgetting the running minimum is the classic bug: code that tracks only the maximum misses cases where two negatives multiply into a new best, like 3, -2 after -4 giving a bigger product than either alone.