Skip to content

Commit

Permalink
Implement largestProductOfThree.js after sorting - O(n * log(n))
Browse files Browse the repository at this point in the history
  • Loading branch information
fay-jai committed Jan 3, 2015
1 parent 61eb59f commit f1cc586
Showing 1 changed file with 28 additions and 0 deletions.
28 changes: 28 additions & 0 deletions largestProductOfThree/largestProductOfThree.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,4 +25,32 @@ var largestProductOfThree = function (array) {
}

return Math.max.apply(null, result);
};

var largestProductOfThree = function (array) {
// Time Complexity: O(n * log(n))

if ( !Array.isArray(array) ) throw new Error('Must provide an Array of numbers');
if ( array.length < 3 ) throw new Error('Array must have at least 3 numbers');

/*
* Array has at least 3 elements
*/

var len = array.length;
var sortedArray, optionA, optionB;

// sort the array => O(n * log(n))
sortedArray = array.sort(function (a, b) { return a - b; });

/*
* The largest product of three numbers can be either:
* 1) the two most negative numbers and the most positive number (option A)
* 2) the three most positive numbers (option B)
*/

optionA = array[0] * array[1] * array[len - 1];
optionB = array[len - 3] * array[len - 2] * array[len - 1];

return Math.max( optionA , optionB );
};

0 comments on commit f1cc586

Please sign in to comment.