Maximum Subarray

medium

Given an integer array nums, find the contiguous subarray — containing at least one number — that has the largest sum, and return that sum.

A subarray is a slice of consecutive elements: you choose where it starts and ends, but you can't skip elements in the middle. Because the subarray must be non-empty, an all-negative array still has an answer — the single largest element.

For nums = [-2, 1, -3, 4, -1, 2, 1, -5, 4], the slice [4, -1, 2, 1] adds up to 6, and no other contiguous stretch does better — so the answer is 6.

Hints

The answer is a single sum, but the subarray must be contiguous — you can't cherry-pick elements. How expensive is it to check every possible contiguous stretch?
As you scan left to right, think about what a running total that has already dropped below zero can possibly do for the elements still ahead of it.
Keep one running sum: extend it while it helps, reset it to the current element the instant it turns negative, and track the best sum you've ever seen. That's Kadane's algorithm.

Common doubts

No — the problem requires a non-empty subarray. So even if every element is negative, you return the largest single element, not 0.
A negative running prefix can only lower the total of whatever follows it. Dropping it and restarting at the current element is never worse, and usually better.
Just the sum, as asked. To recover the actual slice, also track a start and end index whenever you update best or reset the run.

Interview follow-ups

Yes — split at the middle; the best subarray is in the left half, the right half, or crosses the boundary. Recurse on the halves and build the crossing sum by expanding outward from the midpoint, giving O(n log n).
That's 'Maximum Sum Circular Subarray': the answer is either a normal Kadane maximum, or total sum minus the minimum subarray (the wrap case) — with an all-negative array handled specially so you don't return an empty wrap.

Fun facts

  • Kadane's algorithm was devised by Jay Kadane in the 1980s — reportedly in under a minute after the problem was posed — a textbook example of collapsing dynamic programming into a single linear scan.
  • The 'reset a negative running total' trick reappears all over array DP: Maximum Product Subarray, Best Time to Buy and Sell Stock, and the circular-array variant are all descendants.

Asked at

AmazonMicrosoftGoogleBloombergAppleAdobe
Frequently Sometimes Occasionally
Example 1
Input: nums = [-2,1,-3,4,-1,2,1,-5,4]
Output: 6
The subarray [4,-1,2,1] has the largest sum 6.
Example 2
Input: nums = [1]
Output: 1
The subarray [1] has the largest sum 1.
Example 3
Input: nums = [5,4,-1,7,8]
Output: 23
The whole array [5,4,-1,7,8] has the largest sum 23.
Constraints

- 1 <= nums.length <= 10^5 - -10^4 <= nums[i] <= 10^4

Solve this problem →