Skip to content

Instantly share code, notes, and snippets.

@wanderindev
Created July 9, 2022 19:33
Show Gist options
  • Save wanderindev/537cbc458036a24c7cfb6db8df676f74 to your computer and use it in GitHub Desktop.
Save wanderindev/537cbc458036a24c7cfb6db8df676f74 to your computer and use it in GitHub Desktop.
class Solution(object):
def max_subarray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
max_sum = nums[0]
curr_sum = 0
for num in nums:
if curr_sum < 0:
curr_sum = 0
curr_sum += num
max_sum = max(max_sum, curr_sum)
return max_sum
# Test cases
sol = Solution()
nums = [-2, 1, -3, 4, -1, 2, 1, -5, 4]
assert sol.max_subarray(nums) == 6
nums = [1]
assert sol.max_subarray(nums) == 1
nums = [5, 4, -1, 7, 8]
assert sol.max_subarray(nums) == 23
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment