Created
July 2, 2014 23:14
-
-
Save jremmen/f307ef21cc6fb22c06d1 to your computer and use it in GitHub Desktop.
js: maximum sub array in linear time
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
// O(n) | |
Array.prototype.submax = function() { | |
var max = sum = 0; | |
for(var i = 0, l = this.length; i < l; i++) { | |
sum = Math.max(sum + this[i], 0); | |
max = Math.max(max, sum); | |
} | |
return max; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
var max = sum = 0;
should bevar max = 0, sum = 0;
. Otherwise,sum
will be global.