Skip to content

Instantly share code, notes, and snippets.

@gruvw
Created October 7, 2022 13:53
Show Gist options
  • Save gruvw/4d609b727c3663fb3025ea4c37f5c939 to your computer and use it in GitHub Desktop.
Save gruvw/4d609b727c3663fb3025ea4c37f5c939 to your computer and use it in GitHub Desktop.
def max_from(l, s=0):
return max((s := s + e, i) for i, e in enumerate(l))
def max_crossing(l1, l2):
s1, i = max_from(reversed(l1))
s2, j = max_from(iter(l2))
return s1 + s2, (i, len(l1) + j)
def max_subarray(l):
if len(l) == 1:
return l[0], (0, 0)
mid = len(l) // 2
ls = l[:mid], l[mid:]
s1, s2 = map(max_subarray, ls)
s3 = max_crossing(*ls)
return max(s1, s2, s3)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment