Minimum Coin Change Problem
Understand the problem and build a brute force solution.
We'll cover the following
Problem statement
If we have an infinite supply of each of C = { , , … , } valued coins and we want to make a change for a given value (N) of cents, what is the minimum number of coins required to make the change?
Example ->
Input:
coins[] = {25, 10, 5}, N = 30
Output: Minimum 2 coins required
We can use one coin of 25 cents and one of 5 cents.
Input:
coins[] = {9, 6, 5, 1}, N = 13
Output: Minimum 3 coins required
We can use one coin of 6 + 6 + 1 cents coins.
Solution: Recursive approach
Start the solution with cents and in each iteration, find the minimum coins required by dividing the problem into subproblems where we take a coin from {, , …, } and decrease the sum, , by (depending on the coin we took). Whenever becomes 0, we have a possible solution. To find the optimal answer, we return the minimum of all answers for which became 0.
Let’s discuss the recurrence relation now.
-
Base case: If
N == 0
, then 0 coins are required. -
Recursive case: If
N > 0
then, the recurrence relation for this problem can beminCoins(N , coins[0…m-1]) = min {1 + minCoins(N-coin[i], coins[0…m-1])}, where
i
varies from0
tom-1
andcoin[i] <= N
.
Let’s move on to the implementation now.
Level up your interview prep. Join Educative to access 80+ hands-on prep courses.