Created
May 23, 2013 02:03
-
-
Save hisea/5632329 to your computer and use it in GitHub Desktop.
Get the sub-array with the maximum sum
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 find_max_subarray(array) | |
max_sum = current_sum = current_start = start_idx = end_idx = cursor = 0 | |
while cursor < array.length | |
current_test = current_sum + array[cursor] | |
if current_test > 0 | |
if current_sum == 0 | |
current_start = cursor | |
end | |
current_sum += array[cursor] | |
else | |
current_sum = 0 | |
end | |
if current_sum > max_sum | |
max_sum = current_sum | |
start_idx = current_start | |
end_idx = cursor | |
end | |
cursor += 1 | |
end | |
array.slice(start_idx, end_idx - start_idx+1) | |
end | |
a = [ | |
[3,5,1,-9,4], | |
[-1,-2,-1,-5,-1], | |
[5, 21, -30, 6, 9, 15, 20, -80], | |
] | |
a.each do |x| | |
p find_max_subarray(x) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment