Created
September 13, 2019 14:23
-
-
Save priyankvex/f42bb20f82b2c98d10a379b01ec3e4fe to your computer and use it in GitHub Desktop.
Kadane's algorithm
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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