Maximum Product of Three Numbers

Easy

Topics
ArrayMathSorting

Given an integer array nums, find three numbers whose product is maximum and return that product.

Example 1

102132
The answer is the larger of two candidates: the three largest values, or the two most negative times the largest — because two negatives multiply to a positive. Here the winner is the top three, product 6.
Cells are the array values; the small numbers underneath are indices.
Input:  nums = [1,2,3]
Output: 6

Example 2

-40-31-22-13604
Here the winner is the two-negatives case, product 720.
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 largest

Sorting 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

  1. One pass maintaining max1 >= max2 >= max3 and min1 <= min2.
  2. 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))
Asked at Intuit Salesforce
SensAI
Beta
Tap the mic to stop voice mode