JSFiddle - React, Tailwind, and code Playground
by mschock
HTML
<div><span>productWithNegs: </span><span id="productWithNegs"></span></div>
<div><span>productWithoutNegs: </span><span id="productWithoutNegs"></span></div>
<span>highest_product: </span><span id="output"></span>
JavaScript
/** Given an array_of_ints,
find the highest_product you can get from three of the integers.
The input array_of_ints will always have at least three integers. **/
var input = [-1000000, 0, 0, 1, 1, 1, -2, -10, -9];
function find_highest_product(array_of_ints) {
var productWithoutNegs,
productWithNegs,
negative1,
negative2,
positive1,
positive2,
positive3;
for (var i = 0; i < array_of_ints.length; i++) {
var current = array_of_ints[i];
if (current < 0) {
if (!negative1) {
negative1 = current;
} else if (current <= negative1) {
negative2 = negative1;
negative1 = current;
} else if (!negative2) {
negative2 = current;
} else if (current < negative2) {
negative2 = current;
}
} else {
if (!positive1) {
positive1 = current;
} else if (current >= positive1) {
positive3 = positive2;
positive2 = positive1;
positive1 = current;
} else if (!positive2) {
positive2 = current;
} else if (current >= positive2) {
positive3 = positive2;
positive2 = current;
}
}
}
productWithNegs = negative1 * negative2 * positive1;
productWithoutNegs = positive1 * positive2 * positive3;
$('#productWithNegs').html(productWithNegs);
$('#productWithoutNegs').html(productWithoutNegs);
if (!isNaN(productWithNegs) && !isNaN(productWithoutNegs)) {
return productWithNegs > productWithoutNegs ? productWithNegs : productWithoutNegs;
} else if (!isNaN(productWithNegs)) {
return productWithNegs;
} else if (!isNaN(productWithoutNegs)) {
return productWithoutNegs;
} else {
throw new Error('Invalid...