jsは配列の中で3つの数の最大積を求めます.
1539 ワード
// An highlighted block
function maxThreeSum (array) {
var sort_array = array.sort((a, b)=>(a - b)),
product1 = 1,
product2 = 1,
sort_array_length = sort_array.length - 1;
for(var i = sort_array_length; i > sort_array_length - 3; i--) {
product1 = product1 * sort_array[i];
}
product2 = sort_array[0] * sort_array[1] * sort_array[sort_array_length];
if (product1 > product2) return product1;
return product2;
}
実現方法二// An highlighted block
function maxThreeSum (sourceAry) {
var [a, b, c, d, e] = [Infinity, Infinity, -Infinity, -Infinity, -Infinity];
sourceAry.forEach(item => {
if (item < a) {
b = a;
a = item;
} else if (item < b) {
b = item;
}
if (item > e) {
c = d;
d = e;
e = item;
} else if (item > d) {
c = d;
d = item;
} else if (item > c) {
c = item;
}
});
return Math.max(a * b * e, c * d * e);
}