Skip to content

Instantly share code, notes, and snippets.

@ssshukla26
Last active September 25, 2021 00:10
Show Gist options
  • Save ssshukla26/b7b96133e2f3333aee75224acd505336 to your computer and use it in GitHub Desktop.
Save ssshukla26/b7b96133e2f3333aee75224acd505336 to your computer and use it in GitHub Desktop.
Kadane's Algo, this works with -ve elements also
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
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