maximum product
three numbers
algorithm
mathematics
optimization

Maximum Product of Three Numbers

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

Introduction

The maximum product of three numbers problem looks simple until negative numbers enter the picture. The best answer is not always the product of the three largest values, because two very small negative numbers can multiply into a large positive number and beat that obvious choice.

The Key Observation

For any integer array, the maximum product of three numbers must be one of these two candidates:

  • the product of the three largest numbers
  • the product of the two smallest numbers and the largest number

The second case matters because if the two smallest values are large-magnitude negatives, their product becomes positive.

For example:

  • array: [-10, -10, 1, 2, 5]
  • three largest: 1 * 2 * 5 = 10
  • two smallest and largest: -10 * -10 * 5 = 500

The second product wins.

Sorting-Based Solution

The most direct solution is to sort the array and compare those two candidate products:

python
1def maximum_product(nums):
2    nums.sort()
3    return max(
4        nums[-1] * nums[-2] * nums[-3],
5        nums[0] * nums[1] * nums[-1],
6    )
7
8print(maximum_product([-10, -10, 1, 2, 5]))

This is clean and easy to reason about. The cost is O(n log n) because of the sort.

One-Pass O(n) Solution

If you want linear time, track:

  • the three largest values seen so far
  • the two smallest values seen so far

Then compare the same two candidate products at the end:

python
1def maximum_product(nums):
2    max1 = max2 = max3 = float("-inf")
3    min1 = min2 = float("inf")
4
5    for x in nums:
6        if x > max1:
7            max3 = max2
8            max2 = max1
9            max1 = x
10        elif x > max2:
11            max3 = max2
12            max2 = x
13        elif x > max3:
14            max3 = x
15
16        if x < min1:
17            min2 = min1
18            min1 = x
19        elif x < min2:
20            min2 = x
21
22    return max(max1 * max2 * max3, min1 * min2 * max1)
23
24print(maximum_product([1, 2, 3, 4]))
25print(maximum_product([-10, -10, 1, 2, 5]))

This avoids sorting and runs in O(n) time with O(1) extra space.

Why the Logic Is Enough

You do not need to inspect every triple. The maximum product cannot come from an arbitrary middle combination once you realize the sign behavior:

  • large positives help
  • large-magnitude negatives help only in pairs
  • the largest positive value is always a strong candidate in the winning triple

That is why the entire problem collapses to the two-candidate comparison above.

Edge Cases

If the array has exactly three elements, the answer is simply their product.

If all numbers are negative, the result can still be negative. In that situation, the best product is the one closest to zero among valid triples, which the same algorithm still handles correctly.

If zeros are present, they matter naturally. A zero product can beat a negative product when no positive triple exists.

Common Pitfalls

The most common mistake is returning the product of the three largest values without considering the pair of smallest negatives.

Another issue is assuming the answer must be positive. Arrays with only negative values or too many zeros can produce non-positive maximum products.

Developers also overcomplicate the solution with brute force when the two-candidate rule already captures the entire search space.

Summary

  • The answer is always the maximum of two candidate products.
  • Compare the product of the three largest values with the product of the two smallest values and the largest value.
  • Sorting gives a simple O(n log n) solution.
  • Tracking top three and bottom two values gives an O(n) solution.
  • Negative numbers are the reason the problem is more interesting than it first appears.

Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.