40 likes | 155 Views
Greedy strategy At each iteration, it adds a part of the solution. Which part of the solution to add next is determined by a greedy rule . A greedy algorithm may or may not be optimal . The Coin Changing Problem. Given: a large collection of change and a value x .
E N D
Greedy strategy • At each iteration, it adds a part of the solution. • Which part of the solution to add next is determined by a greedy rule. • A greedy algorithm may or may not be optimal
The Coin Changing Problem Given: a large collection of change and a value x. Goal: make change for x using the fewest number of coins Greedy strategy: • choose the most valuable coin, then • subtract its value from X and continue.
e.g.) The Coin Changing Problem • You are given the collection of change (25) (10) (5) (1), and a value x=92 25*3 + 10*1 + 5*1 + 1*2 Using only 7 coins • If you are given the collection of change (12)(5)(1) instead of (25) (10) (5) (1), and a value x=15 12*1+1*3 using 4 coins but there is a better solution 15=5*3 using only 3 coins • The greedy algorithm doesn’t always give the best solution.
Greedy Solution Coin-Changing (d[1]>d[2]>…d[n], x) { i = 1 while (x>0){ C[i]=x/d[i] x=x-c*d[i] i++ } return c[1]+c[2]+…+c[n] } Complexity: O(n)