Created
February 9, 2018 05:49
-
-
Save izmailoff/8ad6a5a3821488f40e6c212bb4843c28 to your computer and use it in GitHub Desktop.
Implements maximum subarray algorithm as described in: https://en.wikipedia.org/wiki/Maximum_subarray_problem
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
def max_subarray(xs): | |
if not xs: | |
return [], 0 | |
start = 0 | |
end = 1 | |
cur_sum = 0 | |
max_sum = xs[0] | |
for i in range(len(xs)): | |
tmp_sum = cur_sum + xs[i] | |
if xs[i] > tmp_sum: | |
cur_sum = xs[i] | |
start = i | |
else: | |
cur_sum = tmp_sum | |
if cur_sum > max_sum: | |
max_sum = cur_sum | |
end = i + 1 | |
return xs[start:end], max_sum | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Python repl: