Created
May 9, 2015 22:45
-
-
Save OskarSigvardsson/51c4ca34e23ea2d8fb86 to your computer and use it in GitHub Desktop.
Maximum subarray problem demonstration
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 max_of_array_ending_at(array, p): | |
if p == 0: | |
return array[0] if array[0] > 0 else 0 | |
subproblem = max_of_array_ending_at(array, p-1) | |
if subproblem + array[p] > 0: | |
return subproblem + array[p] | |
else: | |
return 0 | |
def maximum_subarray_problem(array): | |
return max(max_of_array_ending_at(array, p) for p in range(len(array))) | |
def iterative_version(array): | |
max_ending_here = 0 | |
max_total = 0 | |
for n in array: | |
if max_ending_here + n > 0: | |
max_ending_here += n | |
else: | |
max_ending_here = 0 | |
max_total = max(max_total, max_ending_here) | |
return max_total | |
if __name__ == "__main__": | |
array = [-2, 1, -3, 4, -1, 2, 1, -5, 4] | |
print maximum_subarray_problem(array) | |
print iterative_version(array) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment