Created
January 15, 2016 18:17
-
-
Save huayue21/a302a1663426a663ac8a to your computer and use it in GitHub Desktop.
Maximum Subarray in python.
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
| #!/usr/bin/env python3.2 | |
| # Benjamin James Wright <bwright@cse.unsw.edu.au> | |
| # Maximum Subarray | |
| def max_subarray(L): | |
| current_sum = 0 | |
| current_index = -1 | |
| best_sum = 0 | |
| best_start_index = -1 | |
| best_end_index = -1 | |
| # Iterate over the array. | |
| for i in range(len(L)): | |
| val = current_sum + L[i] | |
| if val > 0: | |
| if current_sum == 0: | |
| current_index = i | |
| current_sum = val | |
| else: | |
| current_sum = 0 | |
| if current_sum > best_sum: | |
| best_sum = current_sum | |
| best_start_index = current_index | |
| best_end_index = i | |
| return L[best_start_index:best_end_index + 1] | |
| if __name__ == '__main__': | |
| print(max_subarray([1,-3,5,-2,9,-8,-6,4])) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment