Created
October 4, 2016 04:52
-
-
Save coldshower/62b3ef50d48a3999a011421bd15d3c41 to your computer and use it in GitHub Desktop.
Max SubArray
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
https://repl.it/Dn8N/2 | |
function maxSub(array) { | |
var maxStart = 0, maxEnd = 0; | |
var start = 0; | |
var currentMax = 0, max = 0; | |
for (var end = 0; end < array.length; end++) { | |
currentMax = currentMax + array[end]; | |
if (currentMax > max) { | |
max = currentMax; | |
maxStart = start; | |
maxEnd = end; | |
} | |
if (currentMax < 0) { | |
currentMax = 0; | |
start = end + 1; | |
} | |
} | |
return array.slice(maxStart, maxEnd + 1); | |
} | |
maxSub([7, 2, -6, 5]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
asdfdsaf