๐บ๐ธ Write a function that finds the largest possible product of the highest three numbers from an array.
Advance
: Make your function handle negative numbers.๐ฆ๐ท Escriba una funciรณn que encuentre el producto mรกximo de los tres nรบmeros mรกs grandes de una lista de numeros.
Advance
: Haz que tu funciรณn pueda lidiar con nรบmeros negativos.๐ฐ๐ท ๋ฐฐ์ด์์ ๊ฐ์ฅ ํฐ ์ธ ์ซ์์ ๊ฐ๋ฅํ ์ต๋ ๊ณฑ์๋ฅผ ์ฐพ๋ ํจ์๋ฅผ ์์ฑํ์ญ์์ค.
Advance
: ์์ฑ๋ ํจ์๊ฐ ์์๋ ์ฒ๋ฆฌํ ์ ์๊ฒ ํ์ญ์์ค.Example:
// Test
const test = largestProductOfThree([2, 1, 3, -4])
// output
console.log(test); // 6
var largestProductOfThree = function(array) {
// Your CODE
};
// Test
largestProductOfThree([2, 1, 3, 7]) // -> 42
largestProductOfThree([2, 5, 13, 7, 11, 3 ]) // -> 1001
largestProductOfThree([7, 5, 3, 2, -11, -13 ]) // -> 105
largestProductOfThree([-31, 34, -37, -17, 41, 19 ]) // -> 40426
largestProductOfThree([40, -50, 20, 5, 30]) // -> 24000
Solution ๐
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.var largestProductOfThree = function(array) { // TODO: everything const sorted = array.sort((a, b) => { return b - a; }); // variable called "result" with value 1 let result = 1; // if(sorted is not empty) // iterate over "sorted", multiply first three element with "result" accumulative for (let i = 0; i < 3; i++) { if (sorted[i] < 0) { // if(sorted[i] is a NEGATIVE number) result = result * Math.abs(sorted[i]); } else { // if(sorted[i] is a POSITIVE number) result = result * sorted[i]; } } return result; };