You get a list of whole numbers, nums. A subarray is a run of one or more numbers that sit next to each other in the list.
Find the subarray whose numbers add up to the most, and return that sum.
Example 1
Input: nums = [3, -5, 2, -1, 4, -6, 1] Output: 5 Why: 2 + (-1) + 4 = 5 is the best run
2 more examples and the constraints
Example 2
Input: nums = [-7, -2, -9] Output: -2 Why: every run is negative; the least bad is [-2]
Example 3
Input: nums = [6, -1, 3] Output: 8 Why: the whole list; the -1 is worth crossing
Constraints
- 1 ≤ length of nums ≤ 100,000
- −10,000 ≤ nums[i] ≤ 10,000
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Every start and endO(n²)
- Divide and conquerO(n log n)
- Kadane’s one passO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 100,000 numbers | Verdict |
|---|---|---|---|
| Every start and end | O(n²) | Mention it, then move on | |
| Divide and conquer | O(n log n) | Passes; the follow-up answer | |
| Kadane’s one pass | O(n) | Best; one pass, no memory |
n = length of nums.
Edge cases to test
- All negative. [-7, -2, -9] must give −2; the subarray cannot be empty.
- One number. The answer is that number, even −10,000.
- A dip worth crossing. [8, −7, 9] gives 10: the 8 still outweighs the −7.
- A dip not worth crossing. [4, −9, 3] gives 4: the run starts over after the −9.
Common mistakes
- Starting best at 0, which returns 0 for an all-negative list.
- Resetting cur to 0 before comparing, so a single negative number is never counted.
- Updating best before cur, which leaves best one step behind.
How to talk through it
- 1Clarify. Can the subarray be empty? Can every number be negative? Do you need the run itself or only its sum?
- 2Give the brute force. Every start, running total to every end; O(n²), too slow for 100,000.
- 3Ask the smaller question. What is the best run ending at i? Extend the one ending at i − 1, or start fresh.
- 4Code Kadane. Two variables, one loop; mention divide and conquer as the O(n log n) follow-up.
- 5Test out loud. Run the all-negative list and a single number before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?