← Core Algorithms
#7 most askedVery commonMediumGreedy

Maximum Subarray

New to Greedy? Learn it from scratch first
Greedy Algorithms β†’
🏒 Asked in real interviews
No reports yet. Were you asked this? Be the first to say where.
I was asked this

Find the contiguous subarray with the largest sum and return that sum.

[-2, 1, -3, 4, -1, 2, 1, -5, 4] β†’ 6 (the subarray [4, -1, 2, 1]).

πŸ§ͺ Practice

Write your solution, then press Run tests. Explain your approach out loud as you go.

Python
def max_subarray(nums):
    pass

Output appears here. Press Run or Ctrl/⌘ + Enter.

Try it first. Struggling for a few minutes is how it sticks.