Maximum Product of Three Numbers
Easy
Topics
Given an integer array nums, find three numbers whose product is maximum and return that product.
Example 1
Input: nums = [1,2,3] Output: 6
Example 2
Input: nums = [-4,-3,-2,-1,60] Output: 720
Constraints
- 3 <= nums.length <= 10^4
- -1000 <= nums[i] <= 1000
Editorial — intuition, approach, complexity and pitfalls
Intuition
With only positive numbers the answer is the three largest. Negatives change that: two negatives multiply to a positive, so the two most negative values paired with the single largest can beat the top three.
Those are the only two candidates. Any product of three must use either zero or two negatives to come out positive (three negatives give a negative, which can only win when every value is negative — and in that case the three largest, being the three closest to zero, is exactly the right answer, and it is already candidate one). So compare:
max1 * max2 * max3 the three largest
min1 * min2 * max1 two most negative, times the largestSorting makes this a two-line solution, and that is the usual answer. But sorting copies or reorders the input for the sake of five values, so a single pass tracking the top three and bottom two is both O(n) time and genuinely O(1) space.
Approach
- One pass maintaining
max1 >= max2 >= max3andmin1 <= min2. - Return the larger of the two candidate products.
Dry Run
nums = [-100, -98, -1, 2, 3, 4]
top three : 4, 3, 2 -> 24
bottom two : -100, -98 -> (-100)(-98)(4) = 39200
answer 39200
nums = [-5,-4,-3,-2,-1] all negative
top three : -1,-2,-3 -> -6
bottom two : -5,-4 times -1 -> -20
answer -6 (the three closest to zero)Complexity
- Time — O(n): one pass. Sorting is O(n log n) for the same answer.
- Space — O(1): five scalars. Worth stating precisely, because
sorted(nums)allocates a full copy — O(n) — and an in-place sort still costs O(log n) of stack and mutates the caller's array. This is the version that actually earns the O(1) claim.
Common Pitfalls
- Returning only the product of the three largest.
[-100,-98,-1,2,3,4]is the counterexample. - Claiming O(1) space while calling
sorted(), which copies. - Considering
min1 * min2 * min3. Three negatives give a negative product, which can never beat the top three. - Taking absolute values to find "the two biggest negatives". A large positive would be picked up too; track the minima directly.
- Overflowing on the multiply. Values reach 1000 so the product fits in 32 bits here, but accumulating in 64-bit is the safer habit and costs nothing.
Full Solution — all languages
class Solution:
def maximumProduct(self, nums):
# sorted() would copy the whole array; one pass over the five values that
# can matter is genuinely O(1) space.
INF = float("inf")
max1 = max2 = max3 = -INF # three largest
min1 = min2 = INF # two smallest, for the two-negatives case
for x in nums:
if x > max1: max1, max2, max3 = x, max1, max2
elif x > max2: max2, max3 = x, max2
elif x > max3: max3 = x
if x < min1: min1, min2 = x, min1
elif x < min2: min2 = x
# Either the three largest, or two large negatives times the largest.
return int(max(max1 * max2 * max3, min1 * min2 * max1))import java.util.*;
class Solution {
public int maximumProduct(int[] nums) {
// Arrays.sort would be O(log n) stack and mutate the caller's array; one pass
// over the five values that can matter is genuinely O(1).
long max1 = Long.MIN_VALUE, max2 = Long.MIN_VALUE, max3 = Long.MIN_VALUE;
long min1 = Long.MAX_VALUE, min2 = Long.MAX_VALUE;
for (int x : nums) {
if (x > max1) { max3 = max2; max2 = max1; max1 = x; }
else if (x > max2) { max3 = max2; max2 = x; }
else if (x > max3) { max3 = x; }
if (x < min1) { min2 = min1; min1 = x; }
else if (x < min2) { min2 = x; }
}
// Either the three largest, or two large negatives times the largest.
return (int) Math.max(max1 * max2 * max3, min1 * min2 * max1);
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int maximumProduct(vector<int>& nums) {
// sort would be O(log n) stack and reorder the caller's vector; one pass over
// the five values that can matter is genuinely O(1).
long long max1 = LLONG_MIN, max2 = LLONG_MIN, max3 = LLONG_MIN;
long long min1 = LLONG_MAX, min2 = LLONG_MAX;
for (int x : nums) {
if (x > max1) { max3 = max2; max2 = max1; max1 = x; }
else if (x > max2) { max3 = max2; max2 = x; }
else if (x > max3) { max3 = x; }
if (x < min1) { min2 = min1; min1 = x; }
else if (x < min2) { min2 = x; }
}
// Either the three largest, or two large negatives times the largest.
return (int) max(max1 * max2 * max3, min1 * min2 * max1);
}
};/**
* @param {number[]} nums
* @return {number}
*/
var maximumProduct = function (nums) {
// Sorting would copy or reorder; one pass over the five values that can matter
// is genuinely O(1) space.
let max1 = -Infinity, max2 = -Infinity, max3 = -Infinity;
let min1 = Infinity, min2 = Infinity;
for (const x of nums) {
if (x > max1) { max3 = max2; max2 = max1; max1 = x; }
else if (x > max2) { max3 = max2; max2 = x; }
else if (x > max3) { max3 = x; }
if (x < min1) { min2 = min1; min1 = x; }
else if (x < min2) { min2 = x; }
}
// Either the three largest, or two large negatives times the largest.
return Math.max(max1 * max2 * max3, min1 * min2 * max1);
};