// 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]));
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.