Maximum Product Subarray
Find the largest product of a run of neighbouring numbers, keeping track of the smallest product as well.
Given an integer array nums
Example 1
Output: 6
Explanation: the run [2, 3] has the product 6.
Example 2
Output: 0
Explanation: the run [0] has the product 0, and every run without the 0 is negative.
Example 3
Output: 24
Explanation: the whole array, because the two negative numbers make a positive product.
The Idea
A run of numbers that sit next to each other in an array is called a subarray. In Example 1, [2, 3][3, -2, 4][2, 3, -2, 4]
Multiply out the runs that start at the first number of Example 1: 2, then 2 × 3 = 6, then 6 × -2 = -12, then -12 × 4 = -48. The single -2 flips the sign of every longer run, so the best of these runs stops just before it, at 6.
Example 3 seems to break that pattern. The array [-2, 3, -4][-2, 3]
Look at the picture below. Under each number, the picture shows two things: the largest product ending here and the smallest product ending here, each with the run that gives it. The bottom row, best so far, is the largest product of any run up to that number.
Under 3, the largest product ending here is 3, from the run [3][-2, 3]
So a negative number turns the smallest product into the largest, and the largest into the smallest. Keeping only the largest product ending at each number would lose the -6, and with it the answer.
Each column of the picture is worked out from the column just before it and the new number, never by looking further back. Building each column from the one before, so that no product is computed twice, is what makes this a dynamic programming solution.
Solution Approach
The simple way is to try every subarray, which is slow, so the faster way needs three things settled: what to keep at each number, how to update it, and where to start.
Trying every subarray
Why not multiply out every run? Pick a start, then extend the run one number at a time, keeping the product as you go. An array of n numbers has n × (n + 1) / 2 runs, so 10 for Example 1 but about half a million for 1,000 numbers. That is O(n²) work, while the columns in the picture need just one pass.
What to keep at each number
What does the next column need from the current one? Only two numbers. In the code, maxHereminHerebestmaxHere
Updating with the next number
Which runs can end at the next number, called xxmaxHere × xminHere × xx
When xmaxHereminHeremax(x, maxHere × x)min(x, minHere × x)
The choice of xxx[-2, 5, 0, 3, 4]
Where to start
What should the three values hold before the loop? The first number on its own, nums[0]best[-3]
Java Solution
The method maxProduct
- First, set
,maxHere andminHere to the first number,best .nums[0] - Walk over the rest of the array with a loop over positions
from 1, and call the number at each positioni .x - If
is negative, swapx andmaxHere , using a temporary variableminHere .t - Set
to the larger ofmaxHere andx , andmaxHere * x to the smaller ofminHere andx .minHere * x - Raise
tobest if it is bigger, and after the loop, returnmaxHere .best
The main
public class MaxProductSubArray {
public static int maxProduct(int[] nums) {
int maxHere = nums[0]; // largest product of a run that ends at the current number
int minHere = nums[0]; // smallest (most negative) product of such a run
int best = nums[0]; // largest product seen anywhere so far
for (int i = 1; i < nums.length; i++) {
int x = nums[i];
if (x < 0) { // multiplying by a negative turns largest into smallest
int t = maxHere;
maxHere = minHere;
minHere = t;
}
maxHere = Math.max(x, maxHere * x); // start fresh at x, or extend the run
minHere = Math.min(x, minHere * x);
best = Math.max(best, maxHere);
}
return best;
}
public static void main(String[] args) {
System.out.println(maxProduct(new int[] {2, 3, -2, 4}));
System.out.println(maxProduct(new int[] {-2, 0, -1}));
System.out.println(maxProduct(new int[] {-2, 3, -4}));
System.out.println(maxProduct(new int[] {-2, 5, 0, 3, 4}));
System.out.println(maxProduct(new int[] {-3}));
System.out.println(maxProduct(new int[] {-1, -2, -3}));
}
}
Running it prints:
6
0
24
12
-3
6
The 24 on the third line is the -6 from the picture at work. A version that keeps only maxHereminHere[-2, 3, -4]
The 12 on the fourth line comes from [3, 4][-2, 5, 0, 3, 4]nums[0][-2, -3]
The original implementation,
Complexity
The work is one pass over the array, with a fixed amount of work at each number.
- Time: O(n), because the loop visits each of the n numbers once and does at most a swap, two multiplications and three
orMath.max calls there.Math.min - Space: O(1), because each column of the picture replaces the one before it, so only
,maxHere ,minHere andbest are kept, however long the array is.t
The same one-pass idea for sums, where negative numbers never flip anything, needs only the largest value ending at each number: see