Skip to content

Instantly share code, notes, and snippets.

@meeDamian
Last active August 29, 2015 14:26
Show Gist options
  • Save meeDamian/035b93915982bc6029fb to your computer and use it in GitHub Desktop.
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…
var arr = [3, 4, 8, 1];
console.log(sth(arr));
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;
}
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