求三个数字乘积的最大

148 阅读1分钟

// 求三个数字乘积的最大,已知这三个数字都是整数、负数或者0,输入数组都是大于三个数字的值

function maxResult(arr){
    let temp = arr.sort((a,b)=>b-a)
    // 
    let max = temp[0]*temp[1]*temp[2]
    // 有可能最后两位是负数
    let max1 = temp[0]*temp[arr.length-1]*temp[arr.length-2]

    return max>max1?max:max1 
}

let test = [3,2,3,4]
let test1 = [1,0,-3,-4]
let test2 = [0,-3,-4,-5,-6]
console.log(maxResult(test))
console.log(maxResult(test1))
console.log(maxResult(test2))