Skip to content

Instantly share code, notes, and snippets.

@zealoushacker
Created June 28, 2012 09:17
Show Gist options
  • Select an option

  • Save zealoushacker/3010137 to your computer and use it in GitHub Desktop.

Select an option

Save zealoushacker/3010137 to your computer and use it in GitHub Desktop.
max subarray (sub array with the greatest sum)
class Array
def max_subarray_last_index
max_sum = new_maxium = last_index = 0
each_with_index do |value, i|
new_maxium = [new_maxium + value, 0].max
# update everything if we found a truly new maximum =)
max_sum, last_index = new_maxium, i if max_sum < new_maxium
end
last_index
end
def max_subarray
self[size - reverse.max_subarray_last_index - 1..max_subarray_last_index]
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment