Maximum Product of Three Numbers (LeetCode 628): Solution and Explanation

Easy
Array
Math
Sorting

Pick three numbers from an integer array so that their product is as large as possible. Negative numbers make it more than a top-three question, but only two candidate products can ever win.

Intuition

With only positive numbers you would multiply the three largest. Negatives complicate that: two negatives multiply to a positive, so -10 and -10 together can be worth more than 5 and 2.

A product of three numbers is positive only if it uses zero or two negatives. Using zero negatives, the best choice is the three largest values. Using two negatives, you want the two with the largest absolute value, which are the two smallest numbers, together with the largest number. Every other triple is beaten by one of these two.

That means you never need the whole sorted array. Five values are enough: the three largest and the two smallest, and a single scan can keep all five up to date.

Approach: One pass, five slots

  1. Keep max1 >= max2 >= max3 and min1 <= min2, all starting empty.
  2. For each number, slide it into the max slots if it beats one of them, shifting the smaller ones down, and do the same for the min slots.
  3. After the scan, compute max1 * max2 * max3 and min1 * min2 * max1.
  4. Return the larger of the two.

Step-by-step example

nums = [1,2,3]
  1. Read 1: it becomes max1 and min1.
  2. Read 2: it becomes max1 (1 moves to max2) and min2.
  3. Read 3: it becomes max1 (2 and 1 shift to max2 and max3). It is not among the two smallest.
  4. Candidates: 3 * 2 * 1 = 6 and 1 * 2 * 3 = 6.
  5. Return 6.

Code: Python, Java, C++

1class Solution:
2    def maximumProduct(self, nums: List[int]) -> int:
3        max1 = max2 = max3 = float('-inf')
4        min1 = min2 = float('inf')
5        for x in nums:
6            if x > max1:
7                max1, max2, max3 = x, max1, max2
8            elif x > max2:
9                max2, max3 = x, max2
10            elif x > max3:
11                max3 = x
12            if x < min1:
13                min1, min2 = x, min1
14            elif x < min2:
15                min2 = x
16        return max(max1 * max2 * max3, min1 * min2 * max1)
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

Each number is compared against at most five slots once.

Space

O(1)

Only the five slot values are stored.

Other approaches

Sort first (time O(n log n), space O(1) to O(n) depending on the sort)

Sort the array and return the larger of a[n-1] * a[n-2] * a[n-3] and a[0] * a[1] * a[n-1]. It is the shortest code and fine for 10^4 numbers, but sorting costs O(n log n).

Try every triple (time O(n^3), space O(1))

Check every combination of three indices. It needs no insight, but at 10^4 numbers that is about 1.7 * 10^11 products.

Common mistakes

  • Returning only the product of the three largest numbers. It fails on [-10,-10,5,2], where the answer is 500.
  • Using min1 * min2 * max3 instead of min1 * min2 * max1. The positive factor should be the largest number.
  • Using >= when shifting the slots, or skipping duplicates. Equal values like [7,7,7] must fill all three max slots.

Frequently asked questions

Can the answer overflow a 32-bit int?

No. Values are at most 1000 in absolute value, so the product is at most 10^9, which fits below 2^31 - 1.

What if all numbers are negative?

Then the best you can do is the three largest (closest to zero), and the first candidate gives exactly that. The second candidate is also negative and at most as large.

Why is the mixed candidate min1 * min2 * max1 and not something with max2?

Once you have fixed two negative factors, you want the largest remaining multiplier, which is max1. Because the array has at least three numbers, the largest element and the two smallest are always three different positions, so the triple is valid.