Created
June 12, 2017 18:39
-
-
Save BeKnowDo/7a3a2009897bc1a09cdac2becfe9120e to your computer and use it in GitHub Desktop.
Kadane's Algorithm
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 maxSequence = function(array) { | |
let currentMax = max = 0 | |
array.map(function(item, index){ | |
// make sure current is greater than zero | |
currentMax = Math.max(0, currentMax + array[index]) | |
// replace max with current max if greater | |
max = Math.max(max, currentMax) | |
}) | |
return max; | |
} | |
console.clear() | |
console.log(maxSequence([-2, 1, -3, 4, -1, 2, 1, -5, 4])) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment