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 is a matroid with and

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

  1. (reject)
  2. return

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 to give a change amount .

Let's call the -problem the computation of the minimum number of coints with values for an amount .

In this case, the original problem is the -problem

Tabulation

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

For example, denomination of , , and .

 
0 1 2 3 4 5 6 7 8 9 10 11 12
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 in the solution of the -problem, then =
  2. If we do use the coin with value in the solution of the -problem, then

Therefore

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.