Greedy algorithms

The best right now · Part of Strategies

Key idea

Practice

6 questions · about 3 min

Explained step by step

Greedy algorithm

A greedy algorithm solves optimization problems by picking, at each decision, the option that looks best at that moment. The idea is to reach the best overall result through good local choices. In coin change: with the pending amount, you take the largest coin that does not go over, and repeat. For 31 with coins of 1, 5, 10 and 20: 20, 10 and 1, 3 coins.

Greedy and dynamic programming both solve optimization problems and both use optimal substructure, but they work differently. Dynamic programming, at each stage, looks at every possible earlier decision and builds the solution from the subproblems'. Greedy moves forward without reconsidering anything: each choice shrinks the remaining problem, until it is done. That is why it is faster: greedy coin change costs O(amt / min(coins)) against O(n × amt).

Solving with greedy takes 3 steps. Analyze the problem: states, objective and constraints. Choose the greedy strategy: how each step chooses, shrinking what is left. And prove it is correct, almost always by contradiction or induction. Choosing the strategy is the hard part: it varies a lot between problems, and some look right but fail in certain cases, like coin change.

There are classic problems solved with greedy. Scheduling tasks: always picking the one that ends first gives the most tasks. Fractional knapsack: take the highest value per kilo first. Buying and selling stock with several trades. Huffman coding: always merge the 2 least frequent nodes to compress without loss. And Dijkstra's algorithm, which finds the shortest paths in graphs with nonnegative weights.

Greedy-choice property

With some coins the greedy does not find the optimum. With [1, 5, 10, 20, 50, 100] it always gets it right. But with [1, 20, 50] and amount 60, it takes 50 and then ten 1s: 11 coins, when 20 + 20 + 20 is 3. With [1, 49, 50] and amount 98, it takes 50 and 48 ones: 49 coins, against 49 + 49, which is 2. For coin change in general, dynamic programming is safer.

Greedy demands more than dynamic programming. It needs 2 properties: the greedy choice, which says picking the best of each moment can always lead to the best overall, and optimal substructure. The greedy choice is easy to state but hard to prove. With coins it is easy to give a counterexample, but saying which coin sets always work is hard: a 2005 paper gives an O(n³) algorithm just to check it.

Terms in this lesson

Arki, the beaver mascot

Your next interview starts with 5 minutes today.

Free on iOS and Android. Start from zero, no account needed.

Key idea

The best right now