You are on page 1of 1

Consider the following problem:

Given k denominations d1, d2, …, dk and a number N. find non negative


integers i1, i2, …, ik such that N= i1d1, i2d2, …, ikdk such that the sum (i1, i2,
…, ik) is small as possible.

(a) Give a Greedy Algorithm to save the problem

while (N > 0)
{
give largest denomination coin ≤ N
reduce N by value of that coin
}

(b) Show that algorithm fails in certain situation

In some (fictional) monetary system, “krons” come in 1 kron, 7 kron, and 10


kron coins
Using a greedy algorithm to count out 15 krons, you would get
 A 10 kron piece
 Five 1 kron pieces, for a total of 15 krons
This requires six coins.

A better solution would be to use two 7 kron pieces and one 1 kron piece
This only requires three coins.
The greedy algorithm results in a solution, but not in an optimal solution

(c) Construct a DP(Dynamic Programming) Algorithm to solve the guarantee


optimality

COINS(N)
1. d[1..n] = {1, 4, 6} // (coinage, for example)
2. for i = 1 to k
3. do c[i, 0] 0
4. for i = 1 to k
5. do for j = 1 to N
6. do if (i = 1 & j < d[i])
7. then c[i, j] 1
8. else if (i = 1)
9. then c[i, j] 1 + c[1, j − d[1]]
10. else if (j < d[i])
11. then c[i, j] c[i − 1, j]
12. else c[i, j] min (c[i − 1, j], 1 + c[i, j − d[i]])
13. return c[k,N]

You might also like