Return the greatest possible product of n numbers from the array 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 first argument and a number, say n, as the second argument.

Our function should calculate and return the greatest possible product of n numbers from the array.

Example

The code for this will be −

const getHighestProduct = (arr, num) => {
   let prod = 1;
   const sorter = (a, b) => a - b;
   arr.sort(sorter);
   if (num > arr.length || num & 2 && arr[arr.length - 1] < 0) {
      return;
   };
   if (num % 2) {
      prod = arr.pop();
      num--;
   };
   while (num) {
      prod *= arr[0] * arr[1] > arr[arr.length - 2] * arr[arr.length - 1]
      ? arr.shift() * arr.shift() : arr.pop() * arr.pop();
      num -= 2;
   };
   return prod;
}
console.log(getHighestProduct([1, 10, -5, 1, -100], 3));
console.log(getHighestProduct([3, 4, 5, 6, 7], 3));
console.log(getHighestProduct([3, 4, -5, -6, -7], 3));

Output

And the output in the console will be −

5000
210
168
raja
Published on 24-Nov-2020 10:28:58
Advertisements