---
title: Greedy Algorithms Explained: Examples, Greedy vs DP
url: https://www.masaischool.com/resources/greedy-algorithms-explained
description: Greedy algorithms explained with Python for activity selection, fractional knapsack, coin change and Huffman coding, plus when greedy fails and greedy vs DP.
updated: 2026-12-01
publisher: Masai (https://www.masaischool.com)
---

# Greedy algorithms explained: examples, when they fail, and greedy vs dynamic programming

> **Short answer**
>
> A greedy algorithm builds an answer by always taking the best-looking choice right now and never reconsidering. It is correct only when that local choice provably leads to a global optimum, as in activity selection, fractional knapsack and Huffman coding. When it is not, as with some coin sets or 0/1 knapsack, use dynamic programming.

Greedy algorithms are short, fast and often wrong. The hard part is never the code; it is knowing whether the greedy rule is safe. This page runs four classic greedy problems in Python 3.9, shows two places where the same instinct fails, explains the exchange argument that proves a rule correct, and ends with a table comparing greedy with [dynamic programming](https://www.masaischool.com/resources/dynamic-programming-explained).

Complexities are in the usual vocabulary of [time complexity and Big O](https://www.masaischool.com/resources/time-complexity-and-big-o-explained); sorting, which most greedy solutions start with, is in [sorting algorithms explained](https://www.masaischool.com/resources/sorting-algorithms-explained).

## What a greedy algorithm is, and when it works

Greedy means: at every step take the option that looks best by some fixed rule, commit to it, and never undo it. It works when the problem has the greedy-choice property (some optimal solution starts with the greedy choice) and optimal substructure (what remains after that choice is a smaller problem of the same kind). If you cannot argue both, test the rule against brute force on small inputs before you trust it.

Most greedy solutions have the same two steps: sort by the right key, then sweep once. The sort dominates, so they typically run in O(n log n). Picking the key is the whole problem, and the same wrong key looks plausible every time, which the next section shows.

## Four greedy problems that work

### Activity selection (meeting rooms)

Given meetings with start and end times in one room, schedule the most that do not overlap. The correct rule is to sort by earliest finish time and take each meeting that starts after the last chosen one ended. Intuitively, finishing early leaves the most room for the rest. Two tempting rules fail: earliest start first, and shortest first. The second is tested in the code below with a trap input, where the shortest meeting blocks two others.def select_activities(acts): acts = sorted(acts, key=lambda a: a[1]) # greedy rule: earliest finish time first chosen, last_end = [], 0 for start, end in acts: if start >= last_end: chosen.append((start, end)) last_end = end return chosen meetings = [(1, 4), (3, 5), (0, 6), (5, 7), (3, 9), (5, 9), (6, 10), (8, 11), (8, 12), (2, 14), (12, 16)] print(select_activities(meetings)) # a tempting but wrong rule: shortest meeting first def shortest_first(acts): chosen = [] for s, e in sorted(acts, key=lambda a: a[1] - a[0]): if all(e <= cs or s >= ce for cs, ce in chosen): chosen.append((s, e)) return sorted(chosen) trap = [(1, 5), (4, 6), (5, 10)] print(len(select_activities(trap)), len(shortest_first(trap)))

Output: [(1, 4), (5, 7), (8, 11), (12, 16)] for the 11 meetings, which is 4 meetings. Then 2 1 for the trap input [(1, 5), (4, 6), (5, 10)]: earliest-finish picks two meetings, shortest-first only one.

### Fractional knapsack

You can take part of an item, so take the items with the best value per kilogram first and split the last one. With rice (₹60, 10 kg), dal (₹100, 20 kg) and sugar (₹120, 30 kg) and a 50 kg bag, the greedy answer is all the rice, all the dal and 20 kg of sugar, worth ₹240. The prices are made-up teaching numbers. The same rule fails when items cannot be split, which is the second half of this code.def fractional_knapsack(items, capacity): # items: (name, value, weight); take best value-per-kg first, split the last item total = 0.0 taken = [] for name, value, weight in sorted(items, key=lambda x: x[1] / x[2], reverse=True): if capacity == 0: break take = min(weight, capacity) total += value * take / weight taken.append((name, take)) capacity -= take return total, taken items = [("rice", 60, 10), ("dal", 100, 20), ("sugar", 120, 30)] print(fractional_knapsack(items, 50)) # the same rule on 0/1 items (cannot split) gives a worse answer than DP def greedy_01(items, cap): total = 0 for _, v, w in sorted(items, key=lambda x: x[1] / x[2], reverse=True): if w <= cap: total += v; cap -= w return total def dp_01(items, cap): dp = [0] * (cap + 1) for _, v, w in items: for c in range(cap, w - 1, -1): dp[c] = max(dp[c], dp[c - w] + v) return dp[cap] print(greedy_01(items, 50), dp_01(items, 50))

Output: (240.0, [('rice', 10), ('dal', 20), ('sugar', 20)]). Then 160 220: on the 0/1 version, greedy by ratio takes rice and dal for 160, but the dal plus sugar choice is worth 220, found by DP.

### Coin change: where greedy works and where it fails

With the Indian denominations 1, 2, 5, 10, 20, 50, 100, 200 and 500, taking the largest coin first gives the fewest coins; the code finds the 289 amount needs 7 coins, the same as the DP answer. With coins 1, 5, 6 and 9, greedy fails on amount 11: it takes 9 + 1 + 1 = 3 coins, but 5 + 6 uses 2. The loop at the bottom finds that 11 is the smallest amount for which greedy loses. Whether a coin set is safe for greedy depends on the set, not on the algorithm, which is why interview solutions should use DP unless the denominations are stated to be canonical.def greedy_coins(coins, amount): used = [] for c in sorted(coins, reverse=True): while amount >= c: amount -= c used.append(c) return used if amount == 0 else None def dp_coins(coins, amount): INF = float("inf") dp = [0] + [INF] * amount for a in range(1, amount + 1): for c in coins: if c <= a: dp[a] = min(dp[a], dp[a - c] + 1) return dp[amount] indian = [1, 2, 5, 10, 20, 50, 100, 200, 500] print(greedy_coins(indian, 289), dp_coins(indian, 289)) odd = [1, 5, 6, 9] print(greedy_coins(odd, 11), dp_coins(odd, 11)) # find the smallest amount where greedy loses, for coins 1, 5, 6, 9 for amt in range(1, 30): g = greedy_coins(odd, amt) if len(g) != dp_coins(odd, amt): print("first amount where greedy loses:", amt, g, dp_coins(odd, amt)) break

Output: [200, 50, 20, 10, 5, 2, 2] 7, then [9, 1, 1] 2, then first amount where greedy loses: 11 [9, 1, 1] 2.

### Huffman coding

Huffman coding gives frequent characters short bit codes and rare ones long codes, so that no code is a prefix of another. The greedy step is to repeatedly merge the two least frequent nodes into one. For aaaaabbbccd (a five times, b three, c two, d once) the code lengths are 1, 2, 3 and 3 bits, for a total of 20 bits against 22 bits with fixed 2-bit codes. The exact bit patterns depend on how ties are broken; the total does not.import heapq from collections import Counter def huffman_codes(text): heap = [[freq, i, ch] for i, (ch, freq) in enumerate(sorted(Counter(text).items()))] heapq.heapify(heap) n = len(heap) while len(heap) > 1: # greedy step: merge the two rarest nodes a = heapq.heappop(heap) b = heapq.heappop(heap) heapq.heappush(heap, [a[0] + b[0], n, (a, b)]) n += 1 codes = {} def walk(node, prefix): label = node[2] if isinstance(label, str): codes[label] = prefix or "0" else: walk(label[0], prefix + "0") walk(label[1], prefix + "1") walk(heap[0], "") return codes text = "aaaaabbbccd" codes = huffman_codes(text) bits = sum(len(codes[ch]) for ch in text) print(codes) print("Huffman bits:", bits, "fixed 2-bit codes:", 2 * len(text))

Output: {'a': '0', 'b': '10', 'd': '110', 'c': '111'} and Huffman bits: 20 fixed 2-bit codes: 22. See the [Wikipedia article](https://en.wikipedia.org/wiki/Huffman_coding) for the proof and history.

## Why a greedy rule is correct: the exchange argument

The standard proof is the exchange argument. Take any optimal solution. Show that you can swap its first choice for the greedy choice without making it worse. Repeat, and you have turned an optimal solution into the greedy one, so the greedy one is optimal too.

For activity selection: let the optimal schedule start with meeting X, and let G be the meeting that finishes earliest of all. G ends no later than X, so replacing X with G cannot create an overlap with the rest of the schedule, and the count stays the same. Now the rest of the problem is the same question on the meetings that start after G ends.

A proof is not a test, but a test catches wrong rules cheaply. The block below compares the earliest-finish rule with brute force over every subset on 300 random inputs of 8 meetings each.# Exchange argument made concrete: for activity selection, swapping the optimal answer's # first meeting for the earliest-finishing one never makes the schedule worse. from itertools import combinations def compatible(sel): sel = sorted(sel, key=lambda a: a[1]) return all(sel[i][1] <= sel[i + 1][0] for i in range(len(sel) - 1)) def best_brute(acts): best = 0 for r in range(len(acts) + 1): for sel in combinations(acts, r): if compatible(sel): best = max(best, r) return best def greedy(acts): n, last = 0, -1 for s, e in sorted(acts, key=lambda a: a[1]): if s >= last: n += 1; last = e return n import random random.seed(7) bad = 0 for _ in range(300): acts = [] for _ in range(8): s = random.randint(0, 20) acts.append((s, s + random.randint(1, 6))) if greedy(acts) != best_brute(acts): bad += 1 print("random cases where greedy != brute force:", bad, "of 300")

Output: random cases where greedy != brute force: 0 of 300. Run the same harness on any greedy rule you invent; for shortest-first, it would flag failures within a few tries, as the trap input showed. Testing on tiny random inputs is also the best way to catch a wrong greedy rule during an interview.

## Greedy vs dynamic programming

|  | Greedy | Dynamic programming |
|---|---|---|
| Decisions | One irrevocable choice per step | Considers all choices and keeps the best, via sub-problems |
| Correctness | Only for problems with the greedy-choice property; needs proof or testing | Correct whenever the problem has optimal substructure |
| Typical time | O(n log n), from the sort | Polynomial in the state space, often O(n^2) or O(n x W) |
| Typical space | O(1) to O(n) | O(states), reducible with rolling rows |
| Examples that fit | Activity selection, fractional knapsack, Huffman, Dijkstra's shortest paths with non-negative weights, minimum spanning trees | 0/1 knapsack, coin change with arbitrary coins, edit distance, LCS |
| How to decide | Try it against brute force on small cases | Check for overlapping sub-problems in the recursion tree |

1. Can you state a rule for the best next choice and sketch why it cannot hurt later? If so, try greedy.
2. Test it on tiny inputs against brute force. One counterexample means stop.
3. If it fails, write the recurrence and use DP: see [dynamic programming examples](https://www.masaischool.com/resources/dynamic-programming-examples) and [types of dynamic programming](https://www.masaischool.com/resources/types-of-dynamic-programming).
4. If you also need every solution, not just the best, use [backtracking](https://www.masaischool.com/resources/backtracking-explained).

The practice order that works: activity selection, then fractional knapsack, then coin change both ways, since that last one trains exactly this judgement. Find problem sets on [coding practice websites](https://www.masaischool.com/resources/tools/coding-practice-websites), and see the full topic map in the [data structures and algorithms path](https://www.masaischool.com/resources/data-structures-and-algorithms).

## Frequently asked questions

### What is a greedy algorithm in simple words?

An algorithm that makes the choice that looks best right now, locks it in, and moves on without ever going back. Picking the largest coin first when giving change is the everyday example. It is fast and simple, but it only gives the best overall answer for certain problems.

### What is the difference between greedy and dynamic programming?

Greedy commits to one choice per step by a fixed rule; dynamic programming compares all choices by solving and caching sub-problems. Greedy is usually faster and simpler but is only correct for some problems. Dynamic programming is correct for any problem with optimal substructure, at the cost of more time and memory.

### When does the greedy algorithm fail?

When a locally best choice blocks a better global result. Coin change with coins 1, 5, 6 and 9 for amount 11 gives 3 coins by greedy but 2 is possible, and 0/1 knapsack by value-per-weight picks worse than the best. In both, use dynamic programming.

### How do you prove a greedy algorithm is correct?

The usual proof is an exchange argument. Take an optimal solution, show that its first choice can be swapped for the greedy choice without getting worse, and repeat. An alternative is showing the greedy solution always stays ahead of any other. In practice, also test against brute force on small inputs.

### Is Dijkstra's algorithm greedy?

Yes. It repeatedly settles the unvisited node with the smallest known distance. That is correct only when edge weights are non-negative, which is why it fails on graphs with negative edges, where Bellman-Ford is used instead. The [applications of graph](https://www.masaischool.com/resources/applications-of-graph-in-data-structure) page shows it in code.

### Is coin change greedy or dynamic programming?

Both appear. For canonical coin systems such as the Indian denominations, greedy gives the minimum. For arbitrary coins it does not, so the general solution is dynamic programming. In an interview, ask whether the denominations are arbitrary; if they are, use DP.
