Skip to content

Instantly share code, notes, and snippets.

@lienista
Last active October 11, 2018 22:56
Show Gist options
  • Select an option

  • Save lienista/81511e19895c7059097face734afe909 to your computer and use it in GitHub Desktop.

Select an option

Save lienista/81511e19895c7059097face734afe909 to your computer and use it in GitHub Desktop.
(Algorithms in Javascript) Leetcode 628. Maximum Product of Three Numbers - Given an integer array, find three numbers whose product is maximum and output the maximum product.
const maximumProduct = (nums) => {
let len = nums.length;
let maxProduct = 1;
if(len===0) return 0;
if(len<=3) {
for(let i=0; i<len; i++){
maxProduct *= nums[i];
}
return maxProduct;
}
var minProdOf2 = nums[0]*nums[1],
maxProdOf2 = minProdOf2,
maxProdOf3 = maxProdOf2*nums[2],
max = Math.max(nums[0], nums[1]),
min = Math.min(nums[0], nums[1]);
for(let i=2; i<len; i++){
maxProdOf3 = Math.max(maxProdOf3, maxProdOf2*nums[i], minProdOf2*nums[i]);
minProdOf2 = Math.min(minProdOf2, min*nums[i], max*nums[i]);
maxProdOf2 = Math.max(maxProdOf2, min*nums[i], max*nums[i]);
max = Math.max(nums[i], max);
min = Math.min(nums[i], min);
}
return maxProdOf3;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment