Created
July 9, 2022 19:33
-
-
Save wanderindev/537cbc458036a24c7cfb6db8df676f74 to your computer and use it in GitHub Desktop.
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 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