-3

Given an example array of [-7, 8, -3, 4, -2, -7, 7], find the highest product that any of three of those numbers may yield.

Related question for solution of the same problem in Python, that did not get an answer with code: Finding highest product of three numbers.

For the example array provided in the first paragraph, expected result is 392.

Przemek
  • 3,855
  • 2
  • 25
  • 33

2 Answers2

0

Greatest product is either max1 * max2 * max3 or max1 * min1 * min2, because multiplying two negative values will give positive one, so:

const highestProduct = arr => {
  const sorted = arr.sort((a, b) => b - a); // Descending (from highest to lowest)
  const n = [...sorted.slice(0, 3), ...sorted.slice(-2)]; // [max1, max2, max3, min1, min2]

  return Math.max(n[0] * n[1] * n[2], n[0] * n[3] * n[4]); // Greater of max1 * max2 * max3 and max1 * min1 * min2
}

console.log(highestProduct([-7, 8, -3, 4, -2, -7, 7]));
Przemek
  • 3,855
  • 2
  • 25
  • 33
0

You can try this

let arr = [-7, 8, -3, 4, -2, -7, 7];

let op = arr.sort((a,b)=>b-a)
let max1 = op.slice(0,3).reduce((a,b)=>a*b,1);
let max2 = op.slice(-2).reduce((a,b)=>a*b,1)*op[0];
let final = Math.max(max1,max2)

console.log(final);
Code Maniac
  • 37,143
  • 5
  • 39
  • 60