mediumArrayDynamic ProgrammingDynamic Programming

Maximum Subarray

mediumTime: O(n)Space: O(1)

Recognize the pattern

maximum sum contiguous subarraycan't skip elements within windowKadane's algorithm

Brute force idea

The naive version of Maximum Subarray sounds like this: Check sum of every subarray. That direct path helps you understand the question, but it tends to treat every possibility as brand new instead of learning from earlier steps.

Better approach

The deeper shift in Maximum Subarray is this: Kadane's: maintain current sum, reset to 0 when it goes negative. Once you hold onto the right piece of information from moment to moment, the problem feels less like trial and error and more like following a shape that was there all along.

Key invariant

At the center of Maximum Subarray is one steady idea: A negative running sum never helps — restart the subarray from the next element. When you keep that truth intact, each local choice supports the larger solution instead of fighting it.

Watch out for

One easy way to drift off course in Maximum Subarray is this: Initializing max to 0 instead of the first element — fails for all-negative arrays. The fix is usually to return to the meaning of each move, not just the steps themselves.

Dynamic Programming Pattern