Maximum Product of Three Numbers
You're given an integer array nums. Pick any three numbers from it whose product is as large as possible, and return that product. Since the array can hold negative values too, the best product might actually come from multiplying the two smallest (most negative) numbers with the single largest positive one.
Input Format
Implement maximumProductOfThreeNumbers(nums). Inputs below show JavaScript function arguments; there is no stdin parsing.
Output Format
Return the result described in the statement.
Sample Input and Output
Example 1 ยท Run Sample
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
Test Cases (2)
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.