Maximum Subarray
Find the largest sum of a contiguous subarray in one pass, dropping any running sum that turns negative.
The problem
You get an integer array nums. Return the largest sum of any non-empty contiguous subarray.
Input nums = [3, -4, 5, -1, 2, -6, 4]
Output 6
5 + (-1) + 2 = 6. Stretching it to the left adds -4 and 3, which lowers the sum.
Input nums = [-3, -1, -2]
Output -1
Every number is negative, so the best subarray is the single largest number.
Key constraint: The array can hold 100,000 numbers, so checking every subarray, about 5 billion of them, is far too slow.
How to spot the pattern
- You want the best contiguous run of numbers.
- A running total that has turned negative can only hurt whatever comes after it.
The idea
Walk from left to right and keep current, the best sum of a subarray that ends at the current number. At a number x, that subarray either continues the previous one or starts fresh at x, and continuing only helps when current is positive, so current = max(x, current + x). This greedy rule of dropping a negative running sum is Kadane's algorithm, and the answer is the largest current you ever see.
Brute force: Add up every subarray with two nested loops, which takes O(n^2) time.
Step by step
- 1Start
currentandbestatnums[0]. - 2For each next number
x, setcurrent = max(x, current + x), which starts fresh when the old sum is negative. - 3Update
best = max(best, current). - 4Return
best.
See the pattern move
The greedy pattern on a small example. Step through it, or press play.
Code
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
best = current = nums[0] # current = best sum of a subarray that ends here
for x in nums[1:]:
# a negative running sum only drags x down, so drop it and start fresh at x
current = max(x, current + x)
best = max(best, current)
return bestComplexity
Time
O(n)
Space
O(1)
One pass that keeps two numbers.
Watch out for
- Starting
bestat 0: when every number is negative, the answer is negative too. - Restarting whenever the running sum dips, instead of only when it drops below 0: in [6, -1, -2, 7] the best is the whole array, 10.
Follow-up questions
Can you return the subarray itself?
Remember where the current run started, move that start whenever you start fresh, and save the start and end whenever best improves.
How would divide and conquer solve it?
Split the array in half. The best subarray lies in the left half, in the right half, or across the middle, and the crossing one is the best suffix of the left plus the best prefix of the right, which gives O(n log n) time.
In Hinglish
Running sum negative ho gaya toh woh aage sirf nuksaan karega, use chhod do aur current number se naya shuru karo. Har step par best update karte raho.