Created
June 28, 2012 09:17
-
-
Save zealoushacker/3010137 to your computer and use it in GitHub Desktop.
max subarray (sub array with the greatest sum)
This file contains hidden or 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
| 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