53. Maximum Subarray
terminate if i==n
max(nums[i], curr_res + nums[i])
max(max_res, curr_res) elseclass Solution:
def maxSubArray(self, nums: List[int]) -> int:
if len(nums) == 1:
return nums[0]
curr = nums[0] # Initialize with the first element
best = nums[0] # Initialize with the first element
for i in range(1, len(nums)): # Start from the second element
curr = max(nums[i], curr + nums[i]) # Choose max between adding or starting fresh
best = max(curr, best) # Update best if current is greater
return best
Last updated