Find the greatest product of three numbers in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

We are required to write a JavaScript function that takes in an array of Numbers as the only. The function should prepare an array of three such elements from the array that yields the greatest products amongst any three elements of the array. The function should finally return the product of those three elements.

For example −

If the input array is −

const arr = [-10, 7, 29, 30, 5, -10, -70];

Then the output should be −

const output = 21000

because the three numbers are 30, -10, -70

We can see that the array can or will probably contain negative elements. Therefore, in such a case the maximum product will be the greater of these two −

min1 * min2 * max1
max1 * max2 * max3

Therefore, we will solve it just like this

Example

Following is the code −

const arr = [-10, 7, 29, 30, 5, -10, -70];
const threeProduct = (arr = []) => {
   const sorter = (a, b) => a -b;
   arr.sort(sorter);
   let pro1 = 1, pro2 = 1;
   let len = arr.length - 1;
   for (let i = len; i > len - 3; i--) {
      pro1 = pro1 * arr[i];
   };
   pro2 = arr[0] * arr[1] * arr[len];
   return Math.max(pro1, pro2);
}
console.log(threeProduct(arr));

Output

Following is the output on console −

21000
raja
Published on 10-Dec-2020 08:11:21
Advertisements