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
/**
* @param {number[]} nums
* @return {number}
*/
//only two possible cases can give max product if we have all positive then last 3 numbers &
// if we have combination of positive negative then multiply first two & with last element
// Reason if we have 2 negative it will turn out to be positive number
var maximumProduct = function (nums) {
let sortedNums = [...nums].sort((a, b) => a - b);
return Math.max(
sortedNums[0] * sortedNums[1] * sortedNums[sortedNums.length - 1],
sortedNums[sortedNums.length - 1] *
sortedNums[sortedNums.length - 2] *
sortedNums[sortedNums.length - 3]
);
};
console.log(maximumProduct([1, 2, 3]));
console.log(maximumProduct([-100, -98, -1, 2, 3, 4]));
Top comments (0)