Skip to content
Problem 628 · LeetCode 628(opens in a new tab)

Maximum Product of Three Numbers

EasyArrays

You are given a list of whole numbers, nums, with at least three entries. Choose three of them, at three different positions, and multiply them together.

Return the largest product you can get this way.

Example 1

Input:  nums = [-6, 2, -5, 3, 1]
Output: 90
Why:    -6 · -5 · 3 = 90; the two negatives cancel out
2 more examples and the constraints

Example 2

Input:  nums = [2, 7, 4, 5]
Output: 140
Why:    the three largest, 7 · 5 · 4

Example 3

Input:  nums = [-4, -2, -9]
Output: -72
Why:    there is only one way to pick three numbers

Constraints

  • 3 ≤ length of nums ≤ 10,000
  • −1,000 ≤ nums[i] ≤ 1,000

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Try every tripleO(n³)
  2. Sort, then two candidatesO(n log n)
  3. One pass, five trackersO(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 10,000 numbersVerdict
Try every tripleO(n³)
Correct, far too slow
Sort, then two candidatesO(n log n)
Passes; short to write
One pass, five trackersO(n)
Best; no sort needed

n = how many numbers are in the list.

Edge cases to test

  • Two large negatives. [-6, 2, -5, 3, 1]: the answer 90 uses both negatives, not the three largest.
  • All negative. [-1, -2, -3, -4] gives −6: pick the three closest to zero.
  • Zeros. [-3, 0, 2, 0] gives 0, better than any negative product.
  • Exactly three numbers. [-4, -2, -9] has one triple, so the answer is −72.
  • Repeated values. [5, 5, 5] gives 125: equal values are still different positions.

Common mistakes

  • Returning only the product of the three largest, which misses two big negatives.
  • Using small1·small2·big3 instead of times big1: the positive partner should be the largest.
  • Skipping the slide-down when a new maximum arrives, so the old big1 is lost instead of moving to big2.

How to talk through it

  1. 1Clarify. Can numbers be negative or zero? Are there always at least three? Can the product overflow?
  2. 2Give the brute force. Try every triple: O(n³), about 166 billion products for 10,000 numbers.
  3. 3Name the two shapes. The winner is the top three, or the bottom two times the top one, because two negatives make a positive.
  4. 4Code the one pass. Track the three largest and two smallest with slide-down updates, then compare both candidates.
  5. 5Test out loud. Run an all-negative list, a list with two big negatives, and one with zeros before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?