This is a classic dynamic programming problem (note first that the greedy algorithm does not always work here!).
Assume the coins are ordered so that a_1 > a_2 > ... > a_k = 1
. We define a new problem. We say that the (i, j)
problem is to find the minimum number of coins making change for j
using coins a_i > a_(i + 1) > ... > a_k
. The problem we wish to solve is (1, j)
for any j
with 1 <= j <= n
. Say that C(i, j)
is the answer to the (i, j)
problem.
Now, consider an instance (i, j)
. We have to decide whether or not we are using one of the a_i
coins. If we are not, we are just solving a (i + 1, j)
problem and the answer is C(i + 1, j)
. If we are, we complete the solution by making change for j - a_i
. To do this using as few coins as possible, we want to solve the (i, j - a_i)
problem. We arrange things so that these two problems are already solved for us and then:
C(i, j) = C(i + 1, j) if a_i > j
= min(C(i + 1, j), 1 + C(i, j - a_i)) if a_i <= j
Now figure out what the initial cases are and how to translate this to the language of your choice and you should be good to go.
If you want to try you hands at another interesting problem that requires dynamic programming, look at Project Euler Problem 67.