Command Palette

Search for a command to run...

← All patterns

Pattern · Greedy & Intervals

Greedy Choice

Make the best-looking choice at each step and never undo it, after proving that this choice is always safe.

Time O(n log n) with sorting, O(n) without · Space O(1)

Taught in Module 33: Greedy Algorithms

Think of it like this

Giving change with the largest coin that fits, again and again: it works for rupee coins, but not for every coin system, so you must check.

Clues that point here

  • → "Minimum number of" with an obvious best next move
  • → Scheduling by earliest end time
  • → Jump game, gas station
  • → Sorting reveals the order to decide in

Not this pattern when

  • ✕ A locally best choice can block a better overall answer (use DP)

The template

A skeleton to adapt. The parts in comments are what changes from problem to problem.

Greedy Choice · template
Arrays.sort(items, (a, b) -> Integer.compare(a[1], b[1]));   // e.g. earliest finish first
int count = 0, lastEnd = Integer.MIN_VALUE;
for (int[] it : items) {
    if (it[0] >= lastEnd) {        // compatible: take it
        count++;
        lastEnd = it[1];
    }
}
return count;

Common versions

  • Jump game I and II
  • Gas station
  • Activity selection
  • Partition labels
  • Task scheduler

Practice problems with this pattern

Related patterns