Coin change problem : Greedy algorithm

Coin change problem

Today, we will discuss a very common problem which can be solved using greedy algorithm. If you are not very familiar with greedy algorithm, here is the gist : At every step of the algorithm, you take the best available option and hope that everything turns optimal at the end which usually does. The problem at hand is coin change problem, which goes like : Given coins of denominations 1,5,10,25,100; find out a way to give a customer an amount with fewest number of coins.   For example, if I ask you to return me change for 30, there are more than two ways to do so like

Amount :  30
Solutions : 3 X 10  ( 3 coins ) 
            6 X 5   ( 6 coins ) 
            1 X 25 + 5 X 1 ( 6 coins )
            1 X 25 + 1 X 5 ( 2 coins )

The last solution is the optimal one as it gives us change only with 2 coins, where as all other solutions provide it in more than two coins. Hope now that problem is clear, let jump on to solution.

Solution for coin change problem using greedy algorithm is very intuitive and called as cashier’s algorithm. Basic principle is : At every iteration for search of a coin, take the largest coin which can fit into remain amount to be changed at that particular time. At the end you will have optimal solution. 🙂 That’s greedy algorithm for you.

Coin change problem : Greedy solution

1. Sort n denomination coins in increasing order of value.
2. Initialize set of coins as empty. S = {}
3. While (amount) is not zero:
   3.1 Ck is largest coin such that x > Ck, 
       if there is no such coin return "no viable solution"
       amount = amount - Ck
       S =  S  U { Ck }

Coin change problem implementation

What will complexity of the code? First we are sorting an array of coins of size n, hence complexity with O(n log n), and then while loop, worst case of it is O(amount), if all we have is coin with 1-denomination. Overall complexity for coin change problem becomes  : O(n log n) + O(amount).

Will this algorithm work for all sort of denominations? Answer is no. It will not give any solution if there is no coin with denomination 1. So be careful while applying this algorithm.

Please share if you have any suggestion or if you want me to write on specific topic. If you liked the post, share it!

Some other greedy algorithm problems:
Interval partitioning
Minimize maximum lateness