Given an unlimited supply of coins of given denominations, find the minimum number of coins required to get the desired change.

For example, consider S = { 1, 3, 5, 7 }.

If the desired change is 15, the minimum number of coins required is 3
 
(7 + 7 + 1) or (5 + 5 + 5) or (3 + 5 + 7)
 
 
If the desired change is 18, the minimum number of coins required is 4
 
(7 + 7 + 3 + 1) or (5 + 5 + 5 + 3) or (7 + 5 + 5 + 1)

Practice this problem

The idea is to use recursion to solve this problem. We recur to see if the total can be reached by including the coin or not for each coin of given denominations. If choosing the current coin resulted in the solution, update the minimum number of coins needed. Finally, return the minimum value we get after exhausting all combinations.

Following is the C++, Java, and Python implementation of the idea:

C++


Download  Run Code

Output:

The minimum number of coins required to get the desired change is 4

Java


Download  Run Code

Output:

The minimum number of coins required to get the desired change is 4

Python


Download  Run Code

Output:

The minimum number of coins required to get the desired change is 4

The time complexity of the above solution is exponential as each recursive call is making n recursive calls.

 
The problem has an optimal substructure as the problem can be broken down into smaller subproblems, which can further be broken down into yet smaller subproblems, and so on. The problem also clearly exhibits overlapping subproblems, so we will end up solving the same subproblem over and over again. The repeated subproblems can be seen by drawing a recursion tree for higher values of n. We know that problems having optimal substructure and overlapping subproblems can be solved by dynamic programming, in which subproblem solutions are saved rather than computed repeatedly.

In the method is demonstrated below in C++, Java, and Python, we use a bottom-up approach, i.e., we solve smaller subproblems first, then solve larger subproblems from them. It computes T[i] for each 1 <= i <= target, which stores the minimum number of coins needed to get a total of i. It makes use of smaller values of i already computed and has the same asymptotic runtime as Memoization but no recursion overhead.

C++


Download  Run Code

Output:

The minimum number of coins required to get the desired change is 4

Java


Download  Run Code

Output:

The minimum number of coins required to get the desired change is 4

Python


Download  Run Code

Output:

The minimum number of coins required to get the desired change is 4

The time complexity of the above solution is O(n.target), where n is the total number of coins and target is the total change required. The auxiliary space required by the program is O(target).

 
Exercise: Find a minimum number of coins required to get the desired change from a limited supply of coins of given denominations.