Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Coin changing algorithm

Tags:

algorithm

Suppose I have a set of coins having denominations a1, a2, ... ak.

One of them is known to be equal to 1.

I want to make change for all integers 1 to n using the minimum number of coins.

Any ideas for the algorithm.

eg. 1, 3, 4 coin denominations
n = 11
optimal selection is 3, 0, 2 in the order of coin denominations.

n = 12
optimal selection is 2, 2, 1.

Note: not homework just a modification of this problem

like image 837
Rohit Banga Avatar asked Dec 31 '09 19:12

Rohit Banga


1 Answers

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.

like image 151
jason Avatar answered Oct 23 '22 02:10

jason