Maximum Subarray
The problem
Section titled “The problem”Given an integer array (it may contain negatives), find the contiguous, non-empty subarray with the largest sum. Return the sum, not the subarray.
nums = [-2, 1, -3, 4, -1, 2, 1, -5, 4] -> 6 ([4, -1, 2, 1])Key insight
Section titled “Key insight”Brute force sums every subarray, which is O(n²) (or O(n³) if you re-add each one). The waste is recomputing overlapping sums.
Think about the best subarray that ends at index i. It either extends the best one
ending at i-1, or starts fresh at i:
cur[i] = max(nums[i], cur[i-1] + nums[i]). The answer is the max of cur over all i.
If the running sum has gone negative, it can only hurt, so you drop it. That is Kadane’s
algorithm. Only the previous cur is needed, so space is O(1).
Show solutionHide solution
def max_sub_array(nums: list[int]) -> int: best = cur = nums[0] # cur = best sum of a subarray ending at i for i in range(1, len(nums)): # nums[1:] would copy the list: O(n) space cur = max(nums[i], cur + nums[i]) # extend the previous subarray, or restart here best = max(best, cur) return bestexport function maxSubArray(nums: number[]): number { let best = nums[0]; let cur = nums[0]; // best sum of a subarray ending at i for (let i = 1; i < nums.length; i++) { cur = Math.max(nums[i], cur + nums[i]); // extend the previous subarray, or restart here best = Math.max(best, cur); } return best;}class Solution { public int maxSubArray(int[] nums) { int best = nums[0]; int cur = nums[0]; // best sum of a subarray ending at i for (int i = 1; i < nums.length; i++) { cur = Math.max(nums[i], cur + nums[i]); // extend the previous subarray, or restart here best = Math.max(best, cur); } return best; }}Complexity
Section titled “Complexity”- Time: O(n) — one pass, constant work per element.
- Space: O(1) — two variables:
curandbest.
Watch out for
Section titled “Watch out for”- All-negative input. Do not start
bestat 0 or resetcurto 0: for[-3, -1, -2]the answer is-1, not 0. Initialize both fromnums[0]. - Restart means
nums[i]alone, not 0. The subarray must be non-empty. - Track
bestseparately fromcur.curcan drop after the peak, so returning it at the end is wrong.
Variations
Section titled “Variations”Maximum Product Subarray (LeetCode 152)
Section titled “Maximum Product Subarray (LeetCode 152)”Same question with products. The trick: a negative number flips the biggest to the
smallest, so track both the max and min product ending at i, and take the best of
nums[i], max*nums[i] and min*nums[i].
Maximum Sum Circular Subarray (LeetCode 918)
Section titled “Maximum Sum Circular Subarray (LeetCode 918)”The array wraps around. The trick: the answer is either the normal Kadane result or
total - (minimum subarray sum), where the wrapped part is everything outside a minimum
subarray. If all numbers are negative, use the normal result.