There is a list of coins :
You want to know the minimum number of coins needed to achieve value , so you asked the two best programmers in the world, Alice and Bob, and each of them proposed a different algorithm:
Alice [Dynamic Programming] :
1 2 3 4 5 6 7 8 |
|
Bob [Greedy] :
1 2 3 4 5 6 7 |
|
Which is the better algorithm? Of course, correctness is your top priority, then the speed.
This section requires Javascript.
You are seeing this because something didn't load right. We suggest you, (a) try
refreshing the page, (b) enabling javascript if it is disabled on your browser and,
finally, (c)
loading the
non-javascript version of this page
. We're sorry about the hassle.
Here is Bob's Greedy Algorithm summarized: Use the largest currency available as many times as you can. For example, if he has $3456: he splits it up into 3 $1000's, 4 $100's, 5 $10's and 6 $1's.
To prove that this indeed yields the minimum number of coins, assume on the contrary it does not. This means that there is a value
V
for which the optimal way to get it in terms of these coins does not use the largest available coin as many times as it could, at some point.Let's say that the largest such coin in this splitting which is not greedily used is of the value 1 0 n . Let us further assume that this solution uses x of those 1 0 n coins less than the greedy solution. Now, it is easy to see that to make up for that extra x ⋅ 1 0 n amount, we have to use either 1 0 x coins of value 1 0 n − 1 , or 1 0 0 x coins of value 1 0 n − 2 , or ...
But this cannot be the case since we said that this solution is optimal. Contradiction!
Hence, the greedy solution is indeed optimal.
Now that we've proved the correctness of the greedy algorithm, we need to show that it is indeed faster.
The dynamic programming algorithm computes the answer for all values from 1 to
V
even irrespective of the coin sizes. However, the greedy algorithm does operations only at points which are multiples of the coin sizes.