function MakeChange (int n)
{
/* Makes change for n units using the minimal number of coins */
const CoinSet = {1, 5, 10, 25, 50, 100}
SolutionSet = empty set ;
sum = 0 ;
while (sum < n) do
{
coin = largest coin in CoinSet such that sum + value(coin) <= n ;
if there is no such coin then return "no solution found"
SolutionSet = SolutionSet + {coin} ;
sum += value(coin) ;
}
return SolutionSet ;
}
The algorithm above works fine. It is a greedy algorithm.
Consider the (old) English coinage which included half-crowns (30 pence),
florins (24 pence), shillings (12 pence), sixpence (6 pence), threepences (3
pence) and pennies (not to mention ha'pennies (1/2 pence) and farthings (1/4
pence). With these coins an algorithm such as the one above does *not* always
produce an optimal solution. (For example, suppose you need to give someone 48
pence.)