Algorithms and Data Structures for Programming Contests
Greedy Algorithms
Discussion
What is it?
- Construct solution piece-by-piece.
- At each step, make best "local" decision — ignore trade-offs.
Example: making change
- Input:
-
Coin denominations
1 = d1 < d2 <
... < dN;
amount A.
- Output:
-
Exact change for A, using as few total coins as possible.
Algorithm
- Give as many coins of denomination
dN as possible,
then as many coins of denomination
dN−1 as possible,
...
Problem
- Works fine for "standard" denominations
(d1 = 1¢,
d2 = 5¢,
d3 = 10¢,
d4 = 25¢).
But does not achieve minimum number of coins for other denominations
(e.g., 1¢, 10¢, 25¢).
Solution?
- Dynamic programming will work, based on the following recursion:
- either optimal solution does not use any coin with value
dN,
- or optimal solution uses one coin with value
dN, along with
a minimum number of coins for amount
A − dN.
How do we know when greedy will work?
- Required property:
for every denomination dn and
for every amount a with
dn ≤ a
< dn+1,
one of the best ways of making change for a uses
at least one coin of denomination
dn.
- This can be checked, on a tedious case-by-case basis,
for the standard denominations
(1¢, 5¢, 10¢, 25¢).
Try it!
© Copyright 2012–2015 François Pitt
<francois.pitt@utoronto.ca>
last updated at 08:24 (EST) on Thu 5 Mar 2015
Algorithms and Data Structures by
François Pitt is licensed under a
Creative
Commons Attribution-ShareAlike 4.0 International License.