Code Logo

Maximum Product of Three Numbers

Published at24 Jul 2026
Easy 0 views
Like0

Given an integer array nums, find the maximum product of any three numbers from the array. The array may contain negative numbers, so the maximum product could be either the product of the three largest numbers or the product of the two smallest negatives times the largest positive.

Sort the array. The answer is max(nums[n-1]*nums[n-2]*nums[n-3], nums[0]*nums[1]*nums[n-1]). The first candidate handles all-positive or mixed arrays where the three largest give the max product. The second handles cases where two very negative numbers produce a large positive when multiplied together and then by the largest positive.

Time is O(n log n) for sorting, space O(1). A linear O(n) approach is also possible but sorting is simpler for this difficulty level.

Edge cases include all negative numbers (product of three largest/least negative), zeros in the array leading to zero product, and duplicate values.

The two-candidate approach works because for any sorted array, the maximum product of three is either the three largest numbers (if all positive or all negative) or two negatives times the largest positive (which becomes positive). The two candidate formulas capture all scenarios: the three largest numbers work when negatives aren't involved, while two negatives times the largest positive captures cases where multiplying two negatives yields a positive product that exceeds the three largest positives.

Example Input & Output

Example 1
Input
[1,2,3,4]
Output
24
Explanation

2*3*4=24.

Example 2
Input
[-5,-4,1,2,3]
Output
60
Explanation

(-5)*(-4)*3=60.

Example 3
Input
[1,1,1,1]
Output
1
Explanation

1*1*1=1.

Example 4
Input
[-1,-2,-3]
Output
-6
Explanation

-1*-2*-3=-6.

Example 5
Input
[1,2,3]
Output
6
Explanation

1*2*3=6.

Algorithm Flow

Recommendation Algorithm Flow for Maximum Product of Three Numbers
Recommendation Algorithm Flow for Maximum Product of Three Numbers

Solution Approach

Sort array. Take max of (largest3 product) and (smallest2 * largest1 product).

function solution(nums) {
  nums.sort(function(a,b){return a-b;});
  var n = nums.length;
  var a = nums[n-1] * nums[n-2] * nums[n-3];
  var b = nums[0] * nums[1] * nums[n-1];
  return Math.max(a, b);
}

Time O(n log n), Space O(1).

Best Answers

java
import java.util.*;
class Solution {
    public int solution(int[] nums) {
        Arrays.sort(nums);
        int n=nums.length;
        return Math.max(nums[n-1]*nums[n-2]*nums[n-3], nums[0]*nums[1]*nums[n-1]);
    }
}