←
Atlas · Finishing techniques · Topic 15 of 18

Greedy

Make the locally best choice at each step, when you can argue it never hurts the final answer.

Watch in Lens

Spot it

Signals in the question

One pass with a simple rule seems to work, and you can argue why it's safe.

"Can you reach…", "minimum number of…", "best run" without needing all combinations.

Sorting first makes the right choice obvious (intervals, meetings, tasks).

The idea

O(n) time · O(1) space

Kadane's rule: walking the list, a running total that has gone negative can only make later numbers smaller, so start fresh. Keep the best total seen; one pass.

Template · Keep or restart (Kadane)

1def max_subarray(nums):2    current = best = nums[0]3    for x in nums[1:]:4        current = max(x, current + x)   # keep the run, or restart5        best = max(best, current)6    return best

The template, filled in for Maximum Subarray. The highlighted line is the part every problem of this kind shares.

The best, free

One of each
WatchGreedy, explainedNeetCode · YouTube · freeReadMaximum subarray problemWikipedia · free

Practice set

Loading your mission…

Common mistakes

1Trusting a greedy rule without a reason: check it against a small counterexample.

2Starting best at 0: an all-negative list then wrongly answers 0.

3Forgetting to sort when the greedy choice depends on order.

Check yourself

Question 1 of 2

In Kadane's algorithm, when do you restart the running total?