Algorithoms Diu W5 L1
Algorithoms Diu W5 L1
CSE@DIU 2
When can we use Greedy algorithms?
We can use a greedy algorithm when the following are true:
CSE@DIU 3
Designing Greedy Algorithms
1. Cast the optimization problem as one for which:
• we make a choice and are left with only one subproblem to
solve
CSE@DIU 4
Example: Making Change
• Instance: amount (in cents) to return to customer
• Problem: do this using fewest number of coins
• Example:
• Assume that we have an unlimited number of coins of various denominations:
• 1c (pennies), 5c (nickels), 10c (dimes), 25c (quarters), 1$ (loonies)
• Objective: Pay out a given sum $5.64 with the smallest number of coins
possible.
CSE@DIU 5
The Coin Changing Problem
• Assume that we have an unlimited number of coins of various
denominations:
• 1c (pennies), 5c (nickels), 10c (dimes), 25c (quarters), 1$ (loonies)
• Objective: Pay out a given sum S with the smallest number of coins
possible.
while S > 0 do
c := value of the largest coin no larger than S;
num := S / c;
pay out num coins of value c;
S := S - num*c;
CSE@DIU 6
Example: Making Change
• E.g.:
$5.64 = $2 +$2 + $1 +
.25 + .25 + .10 +
.01 + .01 + .01 +.01
CSE@DIU 7
Making Change – A big problem
• Example 2: Coins are valued $.30, $.20, $.05, $.01
• Does not have greedy-choice property, since $.40 is best made with two
$.20’s, but the greedy solution will pick three coins (which ones?)
CSE@DIU 8
CSE@DIU 10
CSE@DIU 11
CSE@DIU 12
CSE@DIU 13
CSE@DIU 14
CSE@DIU 15
CSE@DIU 16
CSE@DIU 17
CSE@DIU 18
CSE@DIU 19
CSE@DIU 20
CSE@DIU 21
CSE@DIU 22
CSE@DIU 23
CSE@DIU 24
CSE@DIU 25
CSE@DIU 26
Textbooks & Web References
• Text Book (Chapter 16 and 35)
• Reference book iii (Chapter 17)
• www.geeksforgeeks.org
CSE@DIU 27
Thank you for your patience!
CSE@DIU 28