Skip to content

Instantly share code, notes, and snippets.

@hisea
Created May 23, 2013 02:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hisea/5632329 to your computer and use it in GitHub Desktop.
Save hisea/5632329 to your computer and use it in GitHub Desktop.
Get the sub-array with the maximum sum
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