Skip to problem
←

Maximum Product of Three Numbers

Easy 0 attempts

Given an integer array nums, choose elements at exactly three distinct indices and return their maximum possible product.

The indices need not be consecutive. Equal values at different indices may all be used, but you cannot reuse the same index. The answer may be negative or zero.

For [-4,-3,-2,1,60], choosing -4, -3, and 60 gives 720. For [-5,-4,-3,-2], the maximum product is -24, from -4 × -3 × -2.

Function contract

Implement maximumProductOfThreeNumbers(nums). Receive an integer array containing at least three elements.

Output: Return the maximum product of elements at three distinct indices. Equal values at different indices may each be chosen.

Example 1

Input
nums = [1,2,3,4]
Output
24

Example 2

Input
nums = [-4,-3,-2,1,60]
Output
720
Constraints
  • 3 <= nums.length <= 10^4
  • -1000 <= nums[i] <= 1000

Approach: Sort and Compare

Sort a copy of the array. The maximum product is either from the three largest numbers, or from the two smallest (most negative) numbers multiplied by the largest. Compare both candidates.

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

Time Complexity: O(n log n)

Space Complexity: O(n) for the sorted copy and sorting workspace.

Loading discussion…

Saved in this browser only. Private to you.

JavaScript