Created
December 14, 2017 17:17
-
-
Save messerc/511e0e417d894b6bb0f21481c296f82c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* Write a function that finds the largest possible product of any three numbers | |
* from an array. | |
* | |
* Example: | |
* largestProductOfThree([2, 1, 3, 7]) === 42 | |
* | |
* Extra credit: Make your function handle negative numbers. | |
*/ | |
// Create a convenience function that sorts arrays ascending numerically | |
Array.prototype.sortAscending = function() { | |
this.sort(function(a, b) { | |
return a - b; | |
}); | |
return this; | |
}; | |
var largestProductOfThree = function(array) { | |
// Make a copy of the input array and sort it numerically | |
array = array.slice().sortAscending(); | |
var secondFromLast = array[array.length - 2]; | |
var thirdFromLast = array[array.length - 3]; | |
// this accounts for large negative as well as large positive numbers | |
return array[array.length - 1] * Math.max(secondFromLast * thirdFromLast, array[0] * array[1]); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment