PracticeNeetCode ↗LeetCode ↗
Given an integer array nums, find the contiguous subarray (with at least one number) that has the largest sum, and return that sum.
curSum and maxSum both to nums[0].n: curSum = max(n, curSum + n) — either extend the running subarray or start fresh at n.maxSum = max(maxSum, curSum) after each step.maxSum once the array is exhausted.Time: O(n) — Space: O(1)
def maxSubArray(nums: list[int]) -> int:
curSum = maxSum = nums[0]
for n in nums[1:]:
curSum = max(n, curSum + n)
maxSum = max(maxSum, curSum)
return maxSumHow the solution above works, piece by piece.
curSum = the best sum of a subarray that ends exactly at the current element.curSum = max(n, curSum + n): either extend the previous subarray or start fresh at n. Starting fresh wins exactly when the running sum has gone negative, since a negative prefix only drags the total down.maxSum keeps the best curSum seen anywhere.nums[0] (not 0) makes an all-negative array return its largest element.Running it on nums = [-2, 1, -3, 4, -1, 2, 1, -5, 4]:
curSum currently describes. It restarts at 1 and at 4 because the sum so far was negative. The best window is [4, −1, 2, 1] = 6.