Skip to content

Instantly share code, notes, and snippets.

@hiddenist
Last active March 31, 2023 22:09
Show Gist options
  • Save hiddenist/6938368 to your computer and use it in GitHub Desktop.
Save hiddenist/6938368 to your computer and use it in GitHub Desktop.
Calculate the maximum consecutive sum in a sequence of numbers, keeping track of the range producing the max. Fork of https://gist.github.com/hiddenist/6926596
# 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