Recently I challenged my co-worker to write an algorithm to solve this problem:
Find the least number of coins required that can make any change from
Here's a simple version in Python.
#!/usr/bin/env python
required = []
coins = [25, 10, 5, 1]
t = []
for i in range(1, 100):
while sum(t) != i:
for c in coins:
if sum(t) + c <= i:
t.append(c)
break
for c in coins:
while t.count(c) > required.count(c):
required.append(c)
del t[:]
print required
When run, it prints the following to stdout.
[1, 1, 1, 1, 5, 10, 10, 25, 25, 25]
The code is pretty self-explanatory (thanks Python!), but basically the algorithm is to add the largest coin available that doesn't put you over the current total you're shooting for into your temporary list of coins (t in this case). Once you find the most efficient set of coins for a particular total, make sure there are at least that many of each coin in the required list. Do that for every total from 1 to 99 cents, and you're done.