CSCE 411 Lecture 10

From Notes
Jump to navigation Jump to search
Lecture Slides

« previous | Monday, September 17, 2012 | next »


Matroid Formulation for Greedy Coin Change

Example denomination (1,2,4), value of 9.

We claim that (S,F9) is a matroid with S={1,2,41,42,} and F9={,{1},{2},{41},{42},{1,2},{1,41},{1,42},{2,41},{2,42},{1,2,41},{1,2,42},{1,41,42}}

The greedy algorithm sorts the coins according to values 424121. The algorithm proceeds as follows:

  1. {42}F9
  2. {42,41}F9
  3. {42,41,2}∉F9 (reject)
  4. {42,41,1}F9
  5. return {42,41,1}

By the exchange property, at every intermediate step, there is always another action that can be taken until you reach the maximal state, which should be the optimal solution.


Dynamic Programming

Motivation: We have discussed a greedy algorithm for giving change. However, the greedy algorithm is not optimal for all denominations. Can we design an algorithm to give the optimal result for any denomination?

Dynamic approach: Vary the amount; restrict available coins.

Suppose we have coins with values v1>v2>>vn=1 to give a change amount C.

Let's call the (i,j)-problem the computation of the minimum number of coints with values vi>vi+1>>vn=1 for an amount 1jC.

In this case, the original problem is the (1,C)-problem

Tabulation

Let mij denote the solution to the (i,j)-problem. Thus, mij denotes the minimum number of coins to make change for the amount j using coins with values vi,,vn. It does not store the coin values—only the number of coins.

For example, denomination of v1=10, v2=6, and v3=1.

mij=

  j
0 1 2 3 4 5 6 7 8 9 10 11 12
i 1 0 1 2 3 4 5 6 7 8 9 1 2 2
2 0 1 2 3 4 5 1 2 3 4 5 6 2
3 0 1 2 3 4 5 6 7 8 9 10 11 12

Note the following:

  1. If we do not use the coin with value vi in the solution of the (i,j)-problem, then mij = mi+1,j
  2. If we do use the coin with value vi in the solution of the (i,j)-problem, then mij=1+mi,jvi

Therefore mij={mi+1,jvi>jmin(mi+1,j, 1+mi,jvi)otherwise

Algorithm

def dynamic_coin_change c, v, n
  m = Array.new(n, Array.new(c)) # allocate n x C matrix/array
  1.upto(c) {|i| m[n][i] = i}    # make change for amount i using coins of value v[n] = 1
  {{SOME LOOP} do |i,j|
    if v[i] > j then
      m[i][j] = m[i+1][j]
    else
      m[i][j] = [ m[i+1][j], 1+m[i][j-v[i]] ].min
    end
  end
  m[1][c]
end

Reconstructing the solution: When looking at the final number of coins, look where the answer came from and give value for that coin.