Reputation: 5155
I was given a question:
Given an arrayOfInts, find the highestProduct you can get from three of the integers.
Input: var a = [1,7,9,2]; Expected Output: 7*9*2 = 126
How would we solve this problem? I've written the code but in vain.
function highestProductIntegers(a){
var h1, h2,h3; //three highest number pointers.
a.forEach(function(val, index){
if(index=0){
h1 = val; //assign the first element to h1 (Highest 1)
}
h2 = val; //second to h2
if( val > h1 ){ //if second is greater than h1 make it h1 || h2 || h3
h3 = h2;
h2 = h1;
h1 = val;
}
else if(val<h1 && val > h2) //keep comparing for all elements.
h2 = val;
else if(val < h1 && val < h2)
h3 = val;
else if(val < h1 && val < h2 && val > h3)
h3=val;
});
return h1*h2*h3;
}
Is there any easier or efficient way of solving this problem?
Upvotes: 2
Views: 240
Reputation: 384
function highestProductIntegers(array){
array.sort(function(i,k){return k-i;});
return array[0]*array[1]*array[2];
}
Upvotes: 0
Reputation: 41893
Three short steps.
reduce
function to multiply it and get the result.var a = [17, 1, 7, 9, 2, 5, 9, 15, 12, 44],
r = a.sort((a, b) => b - a).slice(0, 3).reduce((a, b) => a * b);
console.log(r);
Upvotes: 9