Last active
August 29, 2015 14:08
-
-
Save imouaddine/f61376d93c1df5cb197b to your computer and use it in GitHub Desktop.
Largest Sum Contiguous 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
def max_subarray(a) | |
max = - Float::INFINITY | |
max_at = [] | |
sum = 0 | |
sum_at = [] | |
a.each_with_index do |e, i| | |
sum += e | |
sum_at << e | |
sum_at = [e] if sum < e | |
sum = [sum, e].max | |
if sum > max | |
max = sum | |
max_at = sum_at.clone | |
end | |
end | |
return max, max_at | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment