Python Program for Coin Change | DP-7
Last Updated :
09 Nov, 2023
Write a Python program for a given integer array of coins[ ] of size N representing different types of denominations and an integer sum, the task is to find the number of ways to make a sum by using different denominations.
Examples:
Input: sum = 4, coins[] = {1,2,3},
Output: 4
Explanation: there are four solutions: {1, 1, 1, 1}, {1, 1, 2}, {2, 2}, {1, 3}.
Input: sum = 10, coins[] = {2, 5, 3, 6}
Output: 5
Explanation: There are five solutions: {2,2,2,2,2}, {2,2,3,3}, {2,2,6}, {2,3,5} and {5,5}.
Python Program for Coin Change using Recursion:
Recurrence Relation:
count(coins,n,sum) = count(coins,n,sum-count[n-1]) + count(coins,n-1,sum)
For each coin, there are 2 options.
- Include the current coin: Subtract the current coin’s denomination from the target sum and call the count function recursively with the updated sum and the same set of coins i.e., count(coins, n, sum – coins[n-1] )
- Exclude the current coin: Call the count function recursively with the same sum and the remaining coins. i.e., count(coins, n-1,sum ).
The final result will be the sum of both cases.
Base case:
- If the target sum (sum) is 0, there is only one way to make the sum, which is by not selecting any coin. So, count(0, coins, n) = 1.
- If the target sum (sum) is negative or no coins are left to consider (n == 0), then there are no ways to make the sum, so count(sum, coins, 0) = 0.
- Coin Change | DP-7
Below is the Implementation of the above approach:
Python3
def count(coins, n, sum ):
if ( sum = = 0 ):
return 1
if ( sum < 0 ):
return 0
if (n < = 0 ):
return 0
return count(coins, n - 1 , sum ) + count(coins, n, sum - coins[n - 1 ])
coins = [ 1 , 2 , 3 ]
n = len (coins)
print (count(coins, n, 5 ))
|
Time Complexity: O(2sum)
Auxiliary Space: O(sum)
Python Program for Coin Change using Dynamic Programming (Memoization) :
The above recursive solution has Optimal Substructure and Overlapping Subproblems so Dynamic programming (Memoization) can be used to solve the problem. So 2D array can be used to store results of previously solved subproblems.
Step-by-step approach:
- Create a 2D dp array to store the results of previously solved subproblems.
- dp[i][j] will represent the number of distinct ways to make the sum j by using the first i coins.
- During the recursion call, if the same state is called more than once, then we can directly return the answer stored for that state instead of calculating again.
Below is the implementation of the above approach:
Python3
def count(coins, sum , n, dp):
if ( sum = = 0 ):
dp[n][ sum ] = 1
return dp[n][ sum ]
if (n = = 0 or sum < 0 ):
return 0
if (dp[n][ sum ] ! = - 1 ):
return dp[n][ sum ]
dp[n][ sum ] = count(coins, sum - coins[n - 1 ], n, dp) + \
count(coins, sum , n - 1 , dp)
return dp[n][ sum ]
if __name__ = = '__main__' :
tc = 1
while (tc ! = 0 ):
n = 3
sum = 5
coins = [ 1 , 2 , 3 ]
dp = [[ - 1 for i in range ( sum + 1 )] for j in range (n + 1 )]
res = count(coins, sum , n, dp)
print (res)
tc - = 1
|
Time Complexity: O(N*sum), where N is the number of coins and sum is the target sum.
Auxiliary Space: O(N*sum)
Python Program for Coin Change using Dynamic Programming (Tabulation):
- Create a 2D dp array with rows and columns equal to the number of coin denominations and target sum.
dp[0][0]
will be set to
1
which represents the base case where the target sum is 0, and there is only one way to make the change by not selecting any coin.
- Iterate through the rows of the dp array (i from 1 to
n
), representing the current coin being considered.
- The inner loop iterates over the target sums (
j
from 0 to sum
).
- Add the number of ways to make change without using the current coin, i.e.,
dp[i][j] += dp[i-1][j]
.
- Add the number of ways to make change using the current coin, i.e.,
dp[i][j] += dp[i][j-coins[i-1]]
.
dp[n][sum]
will contain the total number of ways to make change for the given target sum using the available coin denominations.
Below is the implementation of the above approach:
Python3
def count(coins, n, target_sum):
dp = [[ 0 for j in range (target_sum + 1 )] for i in range (n + 1 )]
dp[ 0 ][ 0 ] = 1
for i in range ( 1 , n + 1 ):
for j in range (target_sum + 1 ):
dp[i][j] + = dp[i - 1 ][j]
if j - coins[i - 1 ] > = 0 :
dp[i][j] + = dp[i][j - coins[i - 1 ]]
return dp[n][target_sum]
if __name__ = = "__main__" :
coins = [ 1 , 2 , 3 ]
n = 3
target_sum = 5
print (count(coins, n, target_sum))
|
Time complexity : O(N*sum)
Auxiliary Space : O(N*sum)
Python Program for Coin Change using the Space Optimized 1D array:
In the above tabulation approach we are only using dp[i-1][j] and dp[i][j] etc, so we can do space optimization by only using a 1d dp array.
Step-by-step approach:
- Create a 1D dp array,
dp[i]
represents the number of ways to make the sum i
using the given coin denominations.
- The outer loop iterates over the coins, and the inner loop iterates over the target sums. For each
dp[j]
, it calculates the number of ways to make change using the current coin denomination and the previous results stored in dp
.
dp[sum]
contains the total number of ways to make change for the given target sum using the available coin denominations. This approach optimizes space by using a 1D array instead of a 2D DP table.
Below is the implementation of the above approach:
Python
def count(coins, n, sum ):
dp = [ 0 for k in range ( sum + 1 )]
dp[ 0 ] = 1
for i in range ( 0 , n):
for j in range (coins[i], sum + 1 ):
dp[j] + = dp[j - coins[i]]
return dp[ sum ]
coins = [ 1 , 2 , 3 ]
n = len (coins)
sum = 5
x = count(coins, n, sum )
print (x)
|
Time complexity : O(N*sum)
Auxiliary Space : O(sum)
Please refer complete article on Coin Change | DP-7 for more details!
Share your thoughts in the comments
Please Login to comment...