Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Calculate the maximum consecutive sum in a sequence of numbers, keeping track of the range producing the max. Fork of
# Finds the maximum consecutive sum in a list of numbers.
# Returns a three-value tuple containing:
# 0: Starting index of the max sum
# 1: Ending index of the max sum
# 2: The maximum sum
def max_consecutive_sum_idx(values):
if not values:
return None
maxval = None
prev = (-1, -1)
for cur in enumerate(values):
i, v = cur
pi, pv = prev
if prev[1] > 0:
cur = (pi, v + pv)
if maxval is None or cur[1] > maxval[2]:
maxval = (cur[0], i, cur[1])
prev = cur
return maxval
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.