Lecture 2 - Greedy Algorithms.
Lecture 2 - Greedy Algorithms.
Overview
• Greedy algorithms are used to solve optimization problems.
• Problems exhibit optimal substructure.
• Problems also exhibit the greedy-choice property.
• When we have a choice to make, make the one that looks best right
now.
• Make a locally optimal choice in hope of getting a globally optimal
solution.
Greedy Solutions to Optimization Problems
Problem:
• Find the minimum no. of quarters, dimes, nickels, and
pennies that total to a given amount.
Formal Algorithm
• Make change for n units using the least possible number of coins.
• MAKE-CHANGE (n)
C ← {100, 25, 10, 5, 1} // constant.
Sol ← {}; // set that will hold the solution set.
Sum ← 0 sum of item in solution set
WHILE sum not = n
x = largest item in set C such that sum + x ≤ n
IF no such item THEN
RETURN "No Solution"
S ← S {value of x}
sum ← sum + x
RETURN S
The Make-Change algorithm
• The purchase is worth $5.27, how many coins and what
coins does a cash register return after paying a $6 bill?
• For a given amount (e.g. $0.73), use as many quarters ($0.25)
as possible without exceeding the amount.
• Use as many dimes ($.10) for the remainder, then use as many
nickels ($.05) as possible.
• Finally, use the pennies ($.01) for the rest.
Make-Change algorithm