我有一个问题:
给定一个arrayOfInts,找到你可以从三个获得的最高产品 整数。
输入:var a = [1,7,9,2];预期输出:7 * 9 * 2 = 126
我们如何解决这个问题?我写了代码但是徒劳无功。
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;
}
有没有更简单有效的方法来解决这个问题?
答案 0 :(得分:9)
三个简短步骤。
reduce
函数将其相乘并得到结果。
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);
&#13;
答案 1 :(得分:0)
function highestProductIntegers(array){
array.sort(function(i,k){return k-i;});
return array[0]*array[1]*array[2];
}