Greedy
Intermediate · 9 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
A greedy method makes the best-looking choice right now and never looks back. It is worth knowing because, when it works, it gives very fast and simple solutions to scheduling, change-making and packing problems.
Practical use cases
- Web app: Fitting the most talks in one hall. A conference site has 80 requested sessions and one hall. Always picking the session that ends earliest and does not clash leaves the most room for later sessions, so the schedule with the most talks is built in one sorted pass.
- Web app: Giving change at a self-checkout web kiosk. A self-checkout kiosk returning change uses the largest note or coin that fits at each step. With standard currency this gives the fewest coins, and the rule is quick enough that the change is worked out instantly.
- Web app: Job queue with deadlines. A job worker picks the next job with the earliest deadline, which keeps jobs from running late without any heavy planning. The worker needs no complicated scheduling to decide what runs next.
- System: Huffman compression and shortest paths. File compressors repeatedly merge the two least frequent symbols, and Dijkstra's shortest-path method repeatedly takes the nearest unvisited place; both are greedy. These everyday tools use "take the best option right now" and still end up with the best result.
The story: The Seminar Hall Rush
Mrs. Sharma’s school had one auditorium and eleven clubs who each wanted it for an hour or two. The Quiz club wanted 1 to 4, the Dance club 3 to 5, the Science club 0 to 6... The principal sighed: "I want to fit in as many clubs as possible. Nobody may overlap."
Kabir’s first idea: "Pick the club that starts first!" But the Science club started at 0 and hogged the hall until 6, blocking everyone. His second idea: "Pick the shortest talk!" Also fails: a tiny talk in the middle can block two good ones on either side.
Mira thought about what she really wanted: the hall to be free again as soon as possible. "Always pick the talk that ends earliest. Then the hall is free sooner than any other choice, and nothing I can do later is hurt." She picked 1-4, skipped everything that started before 4, took 5-7, then 8-11, then 12-16. Four clubs, and nobody could do better.
That is a greedy algorithm: at each step grab the choice that looks best right now, and never take it back. The smell: "maximum number of...", "minimum number of...", "earliest/latest", "can you reach", and a hunch that a sorted order makes the best local choice also globally safe.
How to spot this problem, and where you need it
You must pick items or steps to get the most, the fewest or the cheapest, and trying every combination is too slow, but there may be a simple rule for the best next choice.
Signs you need it
- The problem asks for maximum non-overlapping tasks, fewest coins, minimum cost, or fewest rooms, and sorting looks natural.
- You can say a rule like "always take the one that ends first" and it feels obviously safe.
- Trying all combinations would explode, and each choice does not block better future choices.
Where to use it in a project
- Scheduling talks, meetings or jobs in limited slots or rooms.
- Change-making, packing and cost-saving calculators in checkout or billing screens.
- Compression, routing and queue tools that already use this idea inside your stack.
The solution
Find a sort order or a rule that tells you the best next choice (earliest end time, biggest coin, shortest job). Sort by it, then walk through the items, taking each one if it still fits. Never undo a choice. Before trusting the rule, test it on small tricky examples, because greedy only works when the local best choice never hurts the final result.
Payoff: Before: checking every subset of 80 talks, impossible. After: one sort and one pass, done instantly.
Explain it like I am 8
You have a short break and many toys to play with. Greedy says: always pick the toy that is over the quickest, so you get time for the next one. You never go back and swap. It works only when "quickest now" truly never hurts later, so you must be able to explain why.
How it works, step by step
- Spot the clue: an optimisation question (most, fewest, longest, cheapest) where choices are made one after another.
- Find the greedy rule: what single "best looking" choice frees the most future options? Here: earliest end time.
- Sort by that rule so the best candidate is always next in line.
- Sweep once: if the candidate fits (
start >= lastEnd) take it and updatelastEnd; otherwise skip it. Decisions are final, with no undo. - Test the rule: try to break it with a tiny counter-example. If you find one, greedy is wrong and you need dynamic programming instead.
The code in four languages
PHP
<?php
// Classic: "Activity selection": the most non-overlapping talks.
function maxTalks(array $talks): array {
usort($talks, fn($a, $b) => $a[1] <=> $b[1]); // greedy rule: earliest END first
$chosen = [];
$lastEnd = -1; // the hall is free from the beginning
foreach ($talks as [$start, $end]) {
if ($start >= $lastEnd) { // fits after the last chosen talk?
$chosen[] = [$start, $end]; // take it, and never take it back
$lastEnd = $end;
}
}
return $chosen;
}
$talks = [[1,4],[3,5],[0,6],[5,7],[3,9],[5,9],[6,10],[8,11],[8,12],[2,14],[12,16]];
$best = maxTalks($talks);
echo count($best), " talks: ", json_encode($best); // 4 talks: [[1,4],[5,7],[8,11],[12,16]]JavaScript
// Classic: "Activity selection": the most non-overlapping talks.
function maxTalks(talks) {
const sorted = [...talks].sort((a, b) => a[1] - b[1]); // greedy rule: earliest END first
const chosen = [];
let lastEnd = -1; // the hall is free from the beginning
for (const [start, end] of sorted) {
if (start >= lastEnd) { // fits after the last chosen talk?
chosen.push([start, end]); // take it, and never take it back
lastEnd = end;
}
}
return chosen;
}
const talks = [[1,4],[3,5],[0,6],[5,7],[3,9],[5,9],[6,10],[8,11],[8,12],[2,14],[12,16]];
const best = maxTalks(talks);
console.log(best.length + ' talks: ' + JSON.stringify(best)); // 4 talks: [[1,4],[5,7],[8,11],[12,16]]Java
import java.util.*;
public class Main {
// Classic: "Activity selection": the most non-overlapping talks.
static List<int[]> maxTalks(int[][] talks) {
int[][] sorted = talks.clone();
Arrays.sort(sorted, (a, b) -> Integer.compare(a[1], b[1])); // greedy rule: earliest END first
List<int[]> chosen = new ArrayList<>();
int lastEnd = -1; // the hall is free from the beginning
for (int[] talk : sorted) {
if (talk[0] >= lastEnd) { // fits after the last chosen talk?
chosen.add(talk); // take it, and never take it back
lastEnd = talk[1];
}
}
return chosen;
}
public static void main(String[] args) {
int[][] talks = {{1,4},{3,5},{0,6},{5,7},{3,9},{5,9},{6,10},{8,11},{8,12},{2,14},{12,16}};
List<int[]> best = maxTalks(talks);
System.out.println(best.size() + " talks: " + Arrays.deepToString(best.toArray()));
// 4 talks: [[1, 4], [5, 7], [8, 11], [12, 16]]
}
}Go
package main
import (
"fmt"
"slices"
)
// maxTalks is the classic "Activity selection": the most non-overlapping talks.
func maxTalks(talks [][2]int) [][2]int {
sorted := slices.Clone(talks)
slices.SortStableFunc(sorted, func(a, b [2]int) int { return a[1] - b[1] }) // greedy rule: earliest END first
var chosen [][2]int
lastEnd := -1 // the hall is free from the beginning
for _, t := range sorted {
if t[0] >= lastEnd { // fits after the last chosen talk?
chosen = append(chosen, t) // take it, and never take it back
lastEnd = t[1]
}
}
return chosen
}
func main() {
talks := [][2]int{{1, 4}, {3, 5}, {0, 6}, {5, 7}, {3, 9}, {5, 9}, {6, 10}, {8, 11}, {8, 12}, {2, 14}, {12, 16}}
best := maxTalks(talks)
fmt.Println(len(best), "talks:", best) // 4 talks: [[1 4] [5 7] [8 11] [12 16]]
}Time: O(n log n) · Extra space: O(n). Sorting dominates; the single greedy sweep is O(n).
Watch out for
- Choosing a greedy rule that "feels" right without testing it. Earliest start and shortest talk both fail on this very problem.
- Using greedy where choices interact, like coin change with coins 1, 3, 4 for amount 6 (greedy gives 4+1+1, but 3+3 is better). Use dynamic programming there.
- Forgetting to sort by the greedy key, then wondering why the answer is random.
Quick check
- Which clue most often hints at a greedy solution?
- "print all possibilities"
- "is there a cycle"
- "reverse the string"
- "find the maximum number of non-overlapping..."
- In talk selection, why sort by END time?
- Short talks are always better
- It makes the list look tidy
- Ending early frees the hall soonest for later talks
- Start times are unreliable
- What is the biggest risk of greedy?
- The local best choice may be globally wrong
- It is too slow
- It cannot be coded
- It needs recursion