Last active
September 25, 2021 00:10
-
-
Save ssshukla26/b7b96133e2f3333aee75224acd505336 to your computer and use it in GitHub Desktop.
Kadane's Algo, this works with -ve elements also
This file contains hidden or 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
from math import inf | |
class Solution: | |
def maxSubArray(self, nums: List[int]) -> int: | |
curr_sum = -inf | |
curr_max = -inf | |
for num in nums: | |
curr_sum = max(curr_sum + num, num) | |
curr_max = max(curr_max, curr_sum) | |
return curr_max |
This file contains hidden or 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: | |
def maxSubArray(self, nums: List[int]) -> int: | |
c = 0 # Current Max | |
m = float("-inf") # Max So Far | |
# For each elements | |
for num in nums: | |
# Update Current Max | |
c = c + num | |
# Check if Current Max is less than current, | |
# if yes, make current max equal to current | |
if c < num: | |
c = num | |
# Mainitain maximum so far | |
m = max(m,c) | |
# return max so far | |
return m | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment