Javatpoint Logo
Javatpoint Logo

C++ coin change program

In 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.

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.

Example

Let us take a input array coins[] = {10, 25, 5}, total coins = 3

We have N = 30.

The output is two as we can use one 25 rupee coin and a 5 rupee coin to make 30. (25 + 5 = 30)

Similarly, coins[] = {1, 9, 6, 5}, total coins = 4

N = 13

The output is three as we need two 6 rupees coins and one 1 rupee coin. (6 + 6 + 1 = 13)

Approach 1

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.

C++ code

Output

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.

Approach 2

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.

C++ code

Output

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.







Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA