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, pick a run of one or more numbers that sit next to each other in the array, with the largest possible product. Return that product.

Example 1
Input: nums = [2, 3, -2, 4]
Output: 6
Explanation: the run [2, 3] has the product 6.
Example 2
Input: nums = [-2, 0, -1]
Output: 0
Explanation: the run [0] has the product 0, and every run without the 0 is negative.
Example 3
Input: nums = [-2, 3, -4]
Output: 24
Explanation: the whole array, because the two negative numbers make a positive product.
Solution

The Idea

A run of numbers that sit next to each other in an array is called a subarray. In Example 1, [2, 3] and [3, -2, 4] are subarrays of [2, 3, -2, 4], but 2 and 4 alone do not form one, because 3 and -2 sit between them.

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] has two negative numbers, and their signs cancel out: -2 × 3 × -4 = 24, the largest product of all. The run [-2, 3] has the product -6, which looks like the worst so far, yet -6 × -4 gives the best product. So which products should we remember as we walk along the array?

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.

For the numbers -2, 3, -4: the largest product ending here is -2, 3, 24, the smallest product ending here is -2, -6, -12, and the best so far is -2, 3, 24. An arrow shows -6 times -4 giving 24.

Under 3, the largest product ending here is 3, from the run [3], and the smallest is -6, from [-2, 3]. Under -4, the largest product ending here is 24. It does not come from the largest product before it, since 3 × -4 = -12. It comes from the smallest one, as the orange arrow shows: -6 × -4 = 24.

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, maxHere is the largest product of a run that ends at the current number, and minHere is the smallest. A third number, best, remembers the largest maxHere seen so far, as in the row labelled "best so far".

Updating with the next number

Which runs can end at the next number, called x? Either the run is x alone, or it is a run that ended at the number before, made one longer. The longer run's product is maxHere × x or minHere × x, so the new largest product is the biggest of x and those two.

When x is negative, the two products trade places: the old smallest gives the new largest, as -6 did under -4. The code handles that by swapping maxHere and minHere first. After the swap, the new largest is max(x, maxHere × x) and the new smallest is min(x, minHere × x).

The choice of x alone matters at a zero. A 0 makes both products 0, and at the next number 0 × x is 0 again. Taking x alone lets a new run begin there, so in [-2, 5, 0, 3, 4], the run starts again at 3 and reaches 3 × 4 = 12.

Where to start

What should the three values hold before the loop? The first number on its own, nums[0], because it is the one run that ends there. Starting best at 0 would be wrong: the array [-3] has the answer -3, and no run has the product 0.

Java Solution

The method maxProduct works in these steps:

  1. First, set maxHere, minHere and best to the first number, nums[0].
  2. Walk over the rest of the array with a loop over positions i from 1, and call the number at each position x.
  3. If x is negative, swap maxHere and minHere, using a temporary variable t.
  4. Set maxHere to the larger of x and maxHere * x, and minHere to the smaller of x and minHere * x.
  5. Raise best to maxHere if it is bigger, and after the loop, return best.

The main method runs the three examples, an array with a zero in the middle, a single negative number, and three negative numbers in a row.

Java
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:

Output
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 maxHere, with no minHere, prints 3 for [-2, 3, -4], because the -6 ending at 3 is thrown away before the -4 arrives.

The 12 on the fourth line comes from [3, 4], after the zero in [-2, 5, 0, 3, 4] set both products to 0. The -3 on the fifth line shows why everything starts at nums[0] and not at 0. The last line, 6, is [-2, -3]: with three negative numbers, the best run leaves out the -1.

The original implementation, MaximumProductSubArray.java, is on GitHub.

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 Math.max or Math.min calls there.
  • Space: O(1), because each column of the picture replaces the one before it, so only maxHere, minHere, best and t are kept, however long the array is.

The same one-pass idea for sums, where negative numbers never flip anything, needs only the largest value ending at each number: see Maximum Subarray.