Skip to content

Instantly share code, notes, and snippets.

@rgee
Created February 14, 2011 20:05
Show Gist options
  • Save rgee/826440 to your computer and use it in GitHub Desktop.
Save rgee/826440 to your computer and use it in GitHub Desktop.
Kadane's algorithm for the maximum sub-array problem
def max_subarray(A):
# (maximum sum, max sum start idx, max sum end idx)
result = (-float('inf'), 0, 0)
current_max_sum = 0
current_start_idx = 1
for i in range(0, len(A)):
current_max_sum = current_max_sum + A[i]
if current_max_sum > result[0]:
result = (current_max_sum, current_start_idx, i)
# If the total contribution of the previous current_start_idx - i elems
# is 0, it is not a part of the max subarray, so we know it occurs
# somewhere in A[i+1...len(A)] if at all.
if current_max_sum < 0:
current_max_sum = 0
current_start_idx = i + 1
return result
if __name__=='__main__':
A = [2, -3, 1, -5, 8, 10]
print max_subarray(A) # Result of above = (18, 4, 5)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment