fullscreen
timer
qrcode
plickers
selector
edit
reset

Greedy Algorithms (4)

COS 320 - Algorithm Design

Greedy Algorithms (4)

Coin Changing

coin changing




coin changing

Goal: Given U.S. currency denominations (\(\{1, 5, 10, 25, 100\}\)), devise a method to pay amount to customer using fewest coins.

Ex: 34¢

Cashier's Algorithm: At each iteration, add coin of the largest value that does not take us past the amount to be paid.

Ex: $2.89

cashier's algorithm

At each iteration, add coin of the largest value that does not take us past the amount to be paid.

Cashiers-Algorithm (x, c1, c2, ..., cn)
    Sort n coin denominations so that 0 < c1 < c2 < ... < cn.
    S <- { }  // multiset of coins selected
    While x > 0
        k <- largest coin denomination ck such that ck <= k
        If no such k, Return "no solution"
        Else
            x <- x - ck
            S <- S | { k };
    Return S

quiz 1: greedy algorithms

live view ]

Is the cashier's algorithm optimal?

  1. Yes, greedy algorithms are always optimal

  2. Yes, for any set of coin denominations \(c_1 < c_2 < \ldots < c_n\) provided \(c_1 = 1\)

  3. Yes, because of special properties of U.S. coin denominations

  4. No.

Cashier's algorithm (for arbitrary coin denominations)

Q: Is Cashier's algorithm optimal for any set of denominations?

A: No. Consider U.S. postage: 1, 10, 21, 34, 70, 100, 350, 1225, 1500.

   1¢;
1¢;
  10¢;
10¢;
  21¢;
21¢;
  34¢;
34¢;
  70¢;
70¢;
 100¢;
100¢;
 350¢;
350¢;
1225¢;
1225¢;
1500¢;
1500¢;

A: No. It may not even lead to a feasible solution if \(c_1 > 1\): 7,8,9

properties of any optimal solution (U.S. coin denominations)

Property: Number of pennies ≤ 4
Pf: Replace 5 pennies with 1 nickel

Property: Number of nickels ≤ 1

Property: Number of quarters ≤ 3

Property: Number of nickels + number of dimes ≤ 2
Pf:

100;
100;
25;
25;
10;
10;
5;
5;
1
1

properties of any optimal solution (U.S. coin denominations)

Theorem: Cashier's Algorithm is optimal for U.S. coins {1,5,10,25,100}

Pf: (by induction on amount to be paid \(x\))

properties of any optimal solution (U.S. coin denominations)

\(k\) \(c_k\) all optimal solutions must satisfy max value of coin denominations \(c_1,c_2,\ldots,c_«k-1»\)
1 1 \(P \leq 4\)
2 5 \(N \leq 1\) \(4c_1 = 4\)
3 10 \(N + D \leq 2\) \(1c_2 + 4c_1 = 5 + 4 = 9\)
4 25 \(Q \leq 3\) \(2c_2 + 4c_1 = 20 + 4 = 24\)
5 100 no limit \(3c_3 + 2c_2 + 4c_1 = 75 + 20 + 4 = 99\)
×