Greedy vs dynamic programming
Greedy algorithms and dynamic programming are both used to optimise a brute force solution.
This lesson shows both of them on one example problem.
Given a list of coins and an amount, find the fewest coins that add up to the amount. Every coin can be used any number of times.
Greedy
Instead of trying every candidate like a brute force solution, a greedy approach follows one rule that picks a single choice at each step, so every other possible choice is skipped.
The code of a greedy solution is usually short, often just one loop. The hard part is to find the rule that allows you to skip the other candidates.
In our example, with coins 1, 5, 10 and 25, we can always take the greatest coin that fits until the amount is reached, instead of checking every possible combination.
The rule works because with these coins, smaller coins that add up to a greater coin can always be replaced with fewer coins, for example 10 + 10 + 5 with one 25. So taking the greatest coin that fits never uses more coins than needed.
Dynamic programming
If the coins are 1, 3 and 4, the greedy approach would not work. For example, if the amount is 6, the greedy approach takes 4, 1 and 1, while 3 and 3 is the correct answer.
With those coins, the problem can be solved with dynamic programming, which stores the answers for smaller inputs and reuses them. It works when the same smaller problems repeat.
Brute force. O(cᵃ) time.
First, let's look at how a brute force solution with backtracking works.
We can generate every possible combination of coins and return the one that uses the fewest coins. With coins and an amount , every call tries up to coins and the calls go up to levels deep.
Top-down. O(a · c) time.
Looking at the recursion tree, you can see repeated work where the function is called with the same input multiple times.
With dynamic programming, we can store the function's return value for each input and reuse it when we need it again.
There are amounts and each of them tries coins once, so it takes time.
Bottom-up. O(a · c) time.
Dynamic programming can also be implemented iteratively.
We can compute the fewest coins needed for each amount one by one starting from 1. Then for each amount we try every coin, the fewest coins for the amount is one plus the fewest coins for the amount minus that coin, which is already computed.