## C++ coin change programIn this article, we will see the most asked interview problem. The coin change problem is a good example of a dynamic programming approach. Now let us understand the problem statement.
Given N and an array(say coins[]) that contains some numbers(coins in rupees). N is a coin, and the array contains various coins. The task is to make the change of N using the coins of the array. Make a change in such a way that a minimum number of coins are used.
Let us take a input array coins[] = {10, 25, 5}, total coins = 3 We have N = 30. The output is Similarly, coins[] = {1, 9, 6, 5}, total coins = 4 N = 13 The output is
The approach uses a recursive method. We start with N, and in each iteration, we divide the problem into smaller subproblems. This is done by taking every coin from the coins array and decrease it from N. The case where N comes to zero gives us the required solution. For an optimal answer, we return the minimum of all combinations.
Minimum coins needed are 2 The above solution does not work for more significant inputs. In this case, the recursive approach fails. Now let us look at an optimized approach.
This approach uses the idea of bottom-up dynamic programming. Since subproblems are computed, again and again, there is a condition of overlapping subproblems. The problem of recomputation can be solved using the property of memoization, i.e., create a dp[] array that stores the computed values at a particular stage. At each stage calculate all the possible combinations. After all the combinations, the last value in the dp[] array gives us the answer.
Minimum coins needed are 2 The time complexity of the code is O(total_coins + sum). This is a much-optimized approach because of storing the results at each stage and utilizing it on the other iterations. |

For Videos Join Our Youtube Channel: Join Now

- Send your Feedback to [email protected]