Last active
August 29, 2015 14:26
-
-
Save meeDamian/035b93915982bc6029fb to your computer and use it in GitHub Desktop.
Write a function that when passed an array of numbers it gives you the max difference between the largest and smallest number ONLY if the small number is in front of the large number, not behind it, so for example: [3,4,8,1] = 5, notice how the biggest difference is between 8 and 1, but because the 1 is after the 8 in the array it shouldn't cou…
This file contains hidden or 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
| var arr = [3, 4, 8, 1]; | |
| console.log(sth(arr)); |
This file contains hidden or 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
| function sth(arr) { | |
| var min = Number.MAX_VALUE; | |
| var diff = Number.MIN_VALUE; | |
| for (var i = 0; i < arr.length; i++) { | |
| var n = arr[i]; | |
| diff = Math.max(diff, n - min); | |
| min = Math.min(min, n); | |
| } | |
| return diff; | |
| } |
This file contains hidden or 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
| function sth(arr) { | |
| var diff = Number.MIN_VALUE; | |
| arr.reduce(function(min, n) { | |
| diff = Math.max(diff, n - min); | |
| return Math.min(min, n); | |
| }, Number.MAX_VALUE); | |
| return diff; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment