Greedy Algorithm to find Minimum number of Coins
Pattern: Candy and assign cookies
With the coins 1, 2, 5, 10, 20, 50, 100, 200, 500 and 2000, always take the largest coin that still fits. For this set the greedy choice is always optimal; for some other coin sets it is not, and you need dynamic programming.
No verified practice link yet. The guide below states the problem in full, so you can still solve it here.
The problem
Using the coins 1, 2, 5, 10, 20, 50, 100, 200, 500 and 2000, with as many of each as needed, make the amount V with
the fewest coins and return them from largest to smallest. 43 gives [20, 20, 2, 1]. The catalogue has no practice link for this one.
Think first
- Which coin should you take first?
- Does taking the largest coin ever cost you later, for these coins?
- When would this greedy fail?
Hints
Brute force, and why it fails
DP over amounts: O(V × coins), which works for any coin set.
The key insight
For this set of coins, the largest coin that fits is always part of some best answer, so a simple loop from the top gives the fewest coins.
Dry run
| left | 23 |
|---|---|
| coins | 20 |
V = 43. The largest coin that fits is 20: take it, 23 left.
The plan
for c in [2000, 500, 200, 100, 50, 20, 10, 5, 2, 1]:
while V >= c: take c; V -= c
Complexity
- Time
O(V / smallest + number of coins)- Space
O(answer)
Each coin taken is one step.
Edge cases
- V = 0: no coins.
- A V equal to a coin: one coin.
- Large V: many 2000s.
I've built my logic, show the code
Java
import java.util.*;
class Solution {
public int[] minCoins(int v) {
int[] coins = {2000, 500, 200, 100, 50, 20, 10, 5, 2, 1}; // largest first
List<Integer> used = new ArrayList<>();
for (int c : coins) {
while (v >= c) { // take this coin while it fits
used.add(c);
v -= c;
}
}
int[] out = new int[used.size()];
for (int i = 0; i < out.length; i++) out[i] = used.get(i);
return out;
}
}C++
class Solution {
public:
vector<int> minCoins(int v) {
int coins[] = {2000, 500, 200, 100, 50, 20, 10, 5, 2, 1}; // largest first
vector<int> used;
for (int c : coins) {
while (v >= c) { // take this coin while it fits
used.push_back(c);
v -= c;
}
}
return used;
}
};Python
class Solution:
def minCoins(self, v: int) -> list[int]:
used = []
for c in (2000, 500, 200, 100, 50, 20, 10, 5, 2, 1): # largest first
while v >= c: # take this coin while it fits
used.append(c)
v -= c
return usedCommon mistakes
- Using the greedy for a coin set where it fails.
- Taking a coin bigger than what is left.