Description
Given an integer array nums, find three numbers whose product is maximum and return the maximum product.
Example 1:
Input: nums = [1,2,3] Output: 6
Example 2:
Input: nums = [1,2,3,4] Output: 24
Example 3:
Input: nums = [-1,-2,-3] Output: -6
Constraints:
3 <= nums.length <= 104-1000 <= nums[i] <= 1000
Solutions
Fastest time achieved, but likely due to small amount of tests.
Language: javascript(2026-07-26 09:14)DONE
CPU Performance97.77%
Memory Performance94.20%
/**
* @param {number[]} nums
* @return {number}
*/
var maximumProduct = function(nums) {
let min1 = Infinity;
let max1 = -Infinity;
let min2 = Infinity;
let max2 = -Infinity;
let res = -Infinity;
for (const num of nums) {
if (min2 < Infinity) {
res = Math.max(res, num * min2, num * max2);
}
if (min1 < Infinity) {
const multMin = num * min1;
const multMax = num * max1;
min2 = Math.min(min2, multMin, multMax);
max2 = Math.max(max2, multMin, multMax);
}
min1 = Math.min(min1, num);
max1 = Math.max(max1, num);
}
return res;
};