Maximum Product of Three Numbers
Given an integer array nums, find three numbers whose product is maximum and return that maximum product. The array may contain both positive and negative numbers, so the maximum product could come from two large negatives multiplied by a large positive.
Example 1:
Input: nums = [1,2,3]
Output: 6
Example 2:
Input: nums = [-100,-98,1,2,3,4]
Output: 39200
Sample Input
—
Sample Output
—
Constraints
- 3 <= nums.length <= 10^4
- -1000 <= nums[i] <= 1000
Test Cases
Case 1
Args: [[1,2,3,4]]
Expected: 24
Case 2
Args: [[-4,-3,-2,1,60]]
Expected: 720
Approach: Sort and Compare
Sort 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.
function maximumProductOfThreeNumbers(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(1)
Saved in this browser only. Private to you.