JSFiddle - React, Tailwind, and code Playground

highestProductOf3

by Varayut Lerdkanlayanawat

JavaScript

// https://www.interviewcake.com/question/highest-product-of-3
function highestProductOf3(arrayOfInts) {
	// Handle edge cases
  if (arrayOfInts.length < 3) {
  	throw new Error('Number of elements must be at least 3');
  }
  
	let highest = Math.max(arrayOfInts[0], arrayOfInts[1]);
  let lowest = Math.min(arrayOfInts[0], arrayOfInts[1]);
  let highestOf2 = arrayOfInts[0] * arrayOfInts[1];
  let lowestOf2 = highestOf2;
  let highestOf3 = -Infinity;
  
  for (let i = 2; i < arrayOfInts.length; i++) {
  	const current = arrayOfInts[i];
    
    highestOf3 = Math.max(highestOf3, highestOf2 * current, lowestOf2 * current);
    
    // Calculate the new highestOf2
    highestOf2 = Math.max(highestOf2, current * highest);
    highest = Math.max(current, highest);
    
    // Calculate the new lowestOf2
    lowestOf2 = Math.min(lowestOf2, current * lowest);
    lowest = Math.min(current, lowest);
	}
  return highestOf3;
}

console.log(highestProductOf3([-10, 5, 3, 7]));