Created
September 30, 2016 03:58
-
-
Save vnprc/a72e6d360da1ed4bc7844c6c219d9f2e to your computer and use it in GitHub Desktop.
find a subsequence of a given sequence with the greatest sum
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
test = [5, -6, 7, 12, -3, 0, -11, -6] | |
def get_max_contiguous_sum(array): | |
results = [] | |
previous_element = 0 | |
for element in array: | |
previous_element = max(element, previous_element + element) | |
results.append(previous_element) | |
return max(results) | |
print("max contiguous array sum: " + str(get_max_contiguous_sum(test))) | |
def get_max_contiguous_array(array): | |
current_array = [array[0]] | |
result_array = [array[0]] | |
#skip the first element | |
for element in array[1:]: | |
if (sum(current_array) + element < element): | |
current_array = [element] | |
else: | |
current_array.append(element) | |
if (sum(current_array) > sum(result_array)): | |
result_array = list(current_array) | |
return result_array | |
print("max contiguous array: " + str(get_max_contiguous_array(test))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment