Skip to content

Instantly share code, notes, and snippets.

@priyankvex
Created September 13, 2019 14:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save priyankvex/f42bb20f82b2c98d10a379b01ec3e4fe to your computer and use it in GitHub Desktop.
Save priyankvex/f42bb20f82b2c98d10a379b01ec3e4fe to your computer and use it in GitHub Desktop.
Kadane's algorithm
class Solution(object):
def solve(self, a):
if not a:
return 0
sum_so_far = a[0]
max_sum = a[0]
for i in range(1, len(a)):
if sum_so_far < 0:
sum_so_far = 0
sum_so_far += a[i]
if sum_so_far > max_sum:
max_sum = sum_so_far
return max_sum
if __name__ == "__main__":
a = [2, -1, 2, 3, 4, -5]
ans = Solution().solve(a)
print(ans)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment