The Wayback Machine - https://web.archive.org/web/20241002210911/https://www.geeksforgeeks.org/coin-change-dp-7/
Open In App

Coin Change – Count Ways to Make Sum

Last Updated : 24 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given an integer array of coins[ ] of size N representing different types of denominations and an integer sum, the task is to count all combinations of coins to make a given value sum.  

Note: Assume that you have an infinite supply of each type of coin. 

Examples: 

Input: sum = 4, coins[] = {1,2,3}
Output: 4
Explanation: there are four solutions: {1, 1, 1, 1}, {1, 1, 2}, {2, 2} and {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}

Input: sum = 10, coins[] = {10}
Output: 1
Explanation: The only is to pick 1 coin of value 10.

Input: sum = 5, coins[] = {4}
Output: 0
Explanation: We cannot make sum 5 with the given coins

Count ways using Recursion:

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

Recurrence Relation: The final result will be the sum of both cases.

count(coins,n,sum) = count(coins, n, sum-count[n-1]) + count(coins, n-1, sum)

Base cases:

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

Below is the Implementation of the above approach.

Coin-Change-With-Recursion

Coin Change Using Recursion

C++
#include <bits/stdc++.h>
using namespace std;

// Returns the count of ways we can
// sum coins[0...n-1] coins to get sum "sum"
int countWays(const vector<int>& coins, int n, int sum) {
  
    // If sum is 0 then there is 1 solution
    // (do not include any coin)
    if (sum == 0) return 1;

    // 0 ways in the following two cases
    if (sum < 0 || n == 0) return 0;

    // count is sum of solutions (i)
    // including coins[n-1] (ii) excluding coins[n-1]
    return countWays(coins, n, sum - coins[n - 1]) + 
            countWays(coins, n - 1, sum);
}

// Driver code
int main() {
    vector<int> coins = {1, 2, 3};
    int sum = 5;
    cout << countWays(coins, coins.size(), sum);
    return 0;
}
C
// Recursive C program for
// coin change problem.
#include <stdio.h>

// Returns the count of ways we can
// sum coins[0...n-1] coins to get sum "sum"
int count(int coins[], int n, int sum)
{
    // If sum is 0 then there is 1 solution
    // (do not include any coin)
    if (sum == 0)
        return 1;

    // If sum is less than 0 then no
    // solution exists
    if (sum < 0)
        return 0;

    // If there are no coins and sum
    // is greater than 0, then no
    // solution exist
    if (n <= 0)
        return 0;

    // count is sum of solutions (i)
    // including coins[n-1] (ii) excluding coins[n-1]
    return count(coins, n - 1, sum)
           + count(coins, n, sum - coins[n - 1]);
}

// Driver program to test above function
int main()
{
    int i, j;
    int coins[] = { 1, 2, 3 };
    int n = sizeof(coins) / sizeof(coins[0]);
    printf("%d ", count(coins, n, 5));
    getchar();
    return 0;
}
Java
// Recursive JAVA program for
// coin change problem.
import java.util.*;
class GFG {

    // Returns the count of ways we can
    // sum coins[0...n-1] coins to get sum "sum"
    static int count(int coins[], int n, int sum)
    {

        // If sum is 0 then there is 1 solution
        // (do not include any coin)
        if (sum == 0)
            return 1;

        // If sum is less than 0 then no
        // solution exists
        if (sum < 0)
            return 0;

        // If there are no coins and sum
        // is greater than 0, then no
        // solution exist
        if (n <= 0)
            return 0;

        // count is sum of solutions (i)
        // including coins[n-1] (ii) excluding coins[n-1]
        return count(coins, n - 1, sum)
            + count(coins, n, sum - coins[n - 1]);
    }

    // Driver code
    public static void main(String args[])
    {
        int coins[] = { 1, 2, 3 };
        int n = coins.length;

        System.out.println(count(coins, n, 5));
    }
}

// This code is contributed by jyoti369
Python
# Recursive Python3 program for
# coin change problem.

# Returns the count of ways we can sum
# coins[0...n-1] coins to get sum "sum"


def count(coins, n, sum):

    # If sum is 0 then there is 1
    # solution (do not include any coin)
    if (sum == 0):
        return 1

    # If sum is less than 0 then no
    # solution exists
    if (sum < 0):
        return 0

    # If there are no coins and sum
    # is greater than 0, then no
    # solution exist
    if (n <= 0):
        return 0

    # count is sum of solutions (i)
    # including coins[n-1] (ii) excluding coins[n-1]
    return count(coins, n - 1, sum) + count(coins, n, sum-coins[n-1])


# Driver program to test above function
coins = [1, 2, 3]
n = len(coins)
print(count(coins, n, 5))

# This code is contributed by Smitha Dinesh Semwal
C#
// Recursive C# program for
// coin change problem.
using System;

class GFG {
    // Returns the count of ways we can
    // sum coins[0...n-1] coins to get sum "sum"
    static int count(int[] coins, int n, int sum)
    {
        // If sum is 0 then there is 1 solution
        // (do not include any coin)
        if (sum == 0)
            return 1;

        // If sum is less than 0 then no
        // solution exists
        if (sum < 0)
            return 0;

        // If there are no coins and sum
        // is greater than 0, then no
        // solution exist
        if (n <= 0)
            return 0;

        // count is sum of solutions (i)
        // including coins[n-1] (ii) excluding coins[n-1]
        return count(coins, n - 1, sum)
            + count(coins, n, sum - coins[n - 1]);
    }

    // Driver program
    public static void Main()
    {

        int[] coins = { 1, 2, 3 };
        int n = coins.Length;
        Console.Write(count(coins, n, 5));
    }
}
// This code is contributed by Sam007
JavaScript
<script>
// Recursive javascript program for
// coin change problem.
   
// Returns the count of ways we can 
// sum coins[0...n-1] coins to get sum "sum"
function count(coins , n , sum )
{

    // If sum is 0 then there is 1 solution 
    // (do not include any coin)
    if (sum == 0)
        return 1;
    
    // If sum is less than 0 then no 
    // solution exists
    if (sum < 0)
        return 0;

    // If there are no coins and sum 
    // is greater than 0, then no
    // solution exist
    if (n <=0)
        return 0;

    // count is sum of solutions (i) 
    // including coins[n-1] (ii) excluding coins[n-1]
    return count( coins, n - 1, sum ) +
           count( coins, n, sum - coins[n - 1] );
}

// Driver program to test above function
var coins = [1, 2, 3];
var n = coins.length;
document.write( count(coins, n, 5));

// This code is contributed by Amit Katiyar 
</script>
PHP
<?php
// Recursive PHP program for
// coin change problem.

// Returns the count of ways we can 
// sum coins[0...n-1] coins to get sum "sum"
function coun($coins, $n, $sum)
{
    
    // If sum is 0 then there is 
    // 1 solution (do not include
    // any coin)
    if ($sum == 0)
        return 1;
    
    // If sum is less than 0 then no 
    // solution exists
    if ($sum < 0)
        return 0;

    // If there are no coins and sum 
    // is greater than 0, then no
    // solution exist
    if ($n <= 0)
        return 0;

    // count is sum of solutions (i) 
    // including coins[n-1] (ii) excluding coins[n-1]
    return coun($coins, $n - 1,$sum ) + 
           coun($coins, $n, $sum - $coins[$n - 1] );
}

    // Driver Code
    $coins = array(1, 2, 3);
    $n = count($coins);
    echo coun($coins, $n, 5); 
    
// This code is contributed by Sam007
?>

Output
 5

Time Complexity: O(2sum)
Auxiliary Space: O(sum)

Count Ways using 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.

Follow the below steps to Implement the idea:

  • Since there are two parameters that change during recursive calls, we create a 2D memo array to store the results of previously solved subproblems.
  • Since the range of recursion parameters goes from 0 to n and 0 to sum, we keep dimensions of the 2D array as (n+1) x (sum + 1)
  • memo[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 using the Memoization:

C++
#include <bits/stdc++.h>
using namespace std;

// Recursive function to count the number of distinct ways
// to make the sum by using n coins
int countWaysRec(vector<int> &coins, int n, int sum, 
                      vector<vector<int>> &memo)
{
    // Base Case
    if (sum == 0)
        return memo[n][sum] = 1;

    // If number of coins is 0 or sum is less than 0 then
    // there is no way to make the sum.
    if (n == 0 || sum < 0)
        return 0;

    // If the subproblem is previously calculated then
    // simply return the result
    if (memo[n][sum] != -1)
        return memo[n][sum];

    // Two options for the current coin
    return memo[n][sum] = countWaysRec(coins, n, sum-coins[n-1], memo) + 
                          countWaysRec(coins, n - 1, sum, memo);
}

// Function to initialize memo array and call countWays
int countWays(vector<int> &coins, int n, int sum) {
    vector<vector<int>> memo(n + 1, vector<int>(sum + 1, -1));
    return countWaysRec(coins, n, sum, memo);
}

int main()
{
    int n = 3, sum = 5;
    vector<int> coins = {1, 2, 3};

    int res = countWays(coins, n, sum);
    cout << res << endl;

    return 0;
}
C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// Recursive function to count the number of distinct ways
// to make the sum by using n coins
int countWaysRec(int coins[], int n, int sum, int *memo[]) {
    // Base Case
    if (sum == 0)
        return memo[n][sum] = 1;

    // If number of coins is 0 or sum is less than 0 then
    // there is no way to make the sum.
    if (n == 0 || sum < 0)
        return 0;

    // If the subproblem is previously calculated then
    // simply return the result
    if (memo[n][sum] != -1)
        return memo[n][sum];

    // Two options for the current coin
    return memo[n][sum] = countWaysRec(coins, n, sum - coins[n - 1], memo) + 
                          countWaysRec(coins, n - 1, sum, memo);
}

// Function to initialize memo array and call countWaysRec
int countWays(int coins[], int n, int sum) {
    int *memo[n+1];
    for (int i = 0; i <= n; i++) {
        memo[i] = (int *)malloc((sum + 1) * sizeof(int));
        memset(memo[i], -1, (sum + 1) * sizeof(int));
    }

    int result = countWaysRec(coins, n, sum, memo);

    for (int i = 0; i <= n; i++) {
        free(memo[i]);
    }

    return result;
}

int main() {
    int coins[] = {1, 2, 3};
    int n = sizeof(coins) / sizeof(coins[0]);
    int sum = 5;

    int res = countWays(coins, n, sum);
    printf("%d\n", res);

    return 0;
}
Java
// Java program for the above approach
import java.util.*;

class GFG {
    // Recursive function to count the numeber of distinct
    // ways to make the sum by using n coins
    static int count(int[] coins, int sum, int n,
                     int[][] dp)
    {
      // Base Case
        if (sum == 0)
            return dp[n][sum] = 1;
      
      // If number of coins is 0 or sum is less than 0 then
        // there is no way to make the sum.
        if (n == 0 || sum<0)
            return 0;

        // If the subproblem is previously calculated then
        // simply return the result
        if (dp[n][sum] != -1)
            return dp[n][sum];

       // Two options for the current coin
        return dp[n][sum]
            = count(coins, sum - coins[n - 1], n, dp)
              + count(coins, sum, n - 1, dp);
    }

    // Driver code
    public static void main(String[] args)
    {
        int tc = 1;
        while (tc != 0) {
            int n, sum;
            n = 3;
            sum = 5;
            int[] coins = { 1, 2, 3 };
            int[][] dp = new int[n + 1][sum + 1];
            for (int[] row : dp)
                Arrays.fill(row, -1);
            int res = count(coins, sum, n, dp);
            System.out.println(res);
            tc--;
        }
    }
}
Python
# Python program for the above approach

# Recursive function to count the numeber of distinct ways
# to make the sum by using n coins


def count(coins, sum, n, dp):
  # Base Case
    if (sum == 0):
        dp[n][sum] = 1
        return dp[n][sum]

     # If number of coins is 0 or sum is less than 0 then there is no way to make the sum.
    if (n == 0 or sum < 0):
        return 0

     # If the subproblem is previously calculated then simply return the result
    if (dp[n][sum] != -1):
        return dp[n][sum]

      # Two options for the current coin

    dp[n][sum] = count(coins, sum - coins[n - 1], n, dp) + \
        count(coins, sum, n - 1, dp)

    return dp[n][sum]


# Driver code
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
C#
// C# program for the above approach
using System;
public class GFG {
    // Recursive function to count the numeber of distinct
    // ways to make the sum by using n coins
    static int count(int[] coins, int sum, int n,
                     int[, ] dp)
    { 
      // Base Case
        if (sum == 0)
            return dp[n, sum] = 1;
      
      // If number of coins is 0 or sum is less than 0 then
        // there is no way to make the sum.
        if (n == 0 || sum < 0)
            return 0;
      
      // If the subproblem is previously calculated then
        // simply return the result
        if (dp[n, sum] != -1)
            return dp[n, sum];
      
       // Two options for the current coin
        return dp[n, sum]
            = count(coins, sum - coins[n - 1], n, dp)
              + count(coins, sum, n - 1, dp);
    }

    // Driver code
    public static void Main(String[] args)
    {
        int tc = 1;
        while (tc != 0) {
            int n, sum;
            n = 3;
            sum = 5;
            int[] coins = { 1, 2, 3 };
            int[, ] dp = new int[n + 1, sum + 1];
            for (int j = 0; j < n + 1; j++) {
                for (int l = 0; l < sum + 1; l++)
                    dp[j, l] = -1;
            }
            int res = count(coins, sum, n, dp);
            Console.WriteLine(res);
            tc--;
        }
    }
}
JavaScript
// javascript program for the above approach

    // Recursive function to count the numeber of distinct ways
    // to make the sum by using n coins
    function count(coins , sum , n,  dp) {
    
        // Base Case
        if (sum == 0)
            return dp[n][sum] = 1;
            
       // If number of coins is 0 or sum is less than 0 then
        // there is no way to make the sum.
        if (n == 0 || sum<0)
            return 0;
            
         // If the subproblem is previously calculated then
        // simply return the result
        if (dp[n][sum] != -1)
            return dp[n][sum];
            
          // Two options for the current coin 
          return dp[n][sum] = count(coins, sum - coins[n - 1], n, dp) + count(coins, sum, n - 1, dp);
        
    }

    // Driver code
    
        var tc = 1;
        while (tc != 0) {
            var n, sum;
            n = 3;
            sum = 5;
            var coins = [ 1, 2, 3 ];
            var dp = Array(n+1).fill().map(() => Array(sum+1).fill(-1));
            
            var res = count(coins, sum, n, dp);
            console.log(res);
            tc--;
        }

Output
5

Time Complexity: O(N*sum), where N is the number of coins and sum is the target sum.
Auxiliary Space: O(N*sum)

Count Ways using Tabulation or DP

We can use the following steps to implement the dynamic programming(tabulation) approach for Coin Change.

  • 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:

C++
#include <bits/stdc++.h>

using namespace std;

// Returns total distinct ways to make sum using n coins of
// different denominations
int count(vector<int>& coins, int n, int sum)
{
    // 2d dp array where n is the number of coin
    // denominations and sum is the target sum
    vector<vector<int> > dp(n + 1, vector<int>(sum + 1, 0));

    // Represents the base case where the target sum is 0,
    // and there is only one way to make change: by not
    // selecting any coin
    dp[0][0] = 1;
    for (int i = 1; i <= n; i++) {
        for (int j = 0; j <= sum; j++) {

            // Add the number of ways to make change without
            // using the current coin,
            dp[i][j] += dp[i - 1][j];

            if ((j - coins[i - 1]) >= 0) {

                // Add the number of ways to make change
                // using the current coin
                dp[i][j] += dp[i][j - coins[i - 1]];
            }
        }
    }
    return dp[n][sum];
}

// Driver Code
int main()
{
    vector<int> coins{ 1, 2, 3 };
    int n = 3;
    int sum = 5;
    cout << count(coins, n, sum);
    return 0;
}
Java
import java.util.*;

public class CoinChangeWays {
    // Returns total distinct ways to make sum using n coins of
    // different denominations
    static int count(List<Integer> coins, int n, int sum) {
        // 2D dp array where n is the number of coin
        // denominations and sum is the target sum
        int[][] dp = new int[n + 1][sum + 1];

        // Represents the base case where the target sum is 0,
        // and there is only one way to make change: by not
        // selecting any coin
        dp[0][0] = 1;
        for (int i = 1; i <= n; i++) {
            for (int j = 0; j <= sum; j++) {
                // Add the number of ways to make change without
                // using the current coin
                dp[i][j] += dp[i - 1][j];

                if ((j - coins.get(i - 1)) >= 0) {
                    // Add the number of ways to make change
                    // using the current coin
                    dp[i][j] += dp[i][j - coins.get(i - 1)];
                }
            }
        }
        return dp[n][sum];
    }

    // Driver Code
    public static void main(String[] args) {
        List<Integer> coins = Arrays.asList(1, 2, 3);
        int n = 3;
        int sum = 5;
        System.out.println(count(coins, n, sum));
    }
}
// This code is contributed by Veerendra_Singh_Rajpoot
Python
# Function to calculate the total distinct ways to make a sum using n coins of different denominations
def count(coins, n, target_sum):
    # 2D dp array where n is the number of coin denominations and target_sum is the target sum
    dp = [[0 for j in range(target_sum + 1)] for i in range(n + 1)]

    # Represents the base case where the target sum is 0, and there is only one way to make change: by not selecting any coin
    dp[0][0] = 1
    for i in range(1, n + 1):
        for j in range(target_sum + 1):
            # Add the number of ways to make change without using the current coin
            dp[i][j] += dp[i - 1][j]

            if j - coins[i - 1] >= 0:
                # Add the number of ways to make change using the current coin
                dp[i][j] += dp[i][j - coins[i - 1]]

    return dp[n][target_sum]

# Driver Code
if __name__ == "__main__":
    coins = [1, 2, 3]
    n = 3
    target_sum = 5
    print(count(coins, n, target_sum))
C#
using System;
using System.Collections.Generic;

class Program {
    // Returns total distinct ways to make sum using n coins
    // of different denominations
    static int Count(List<int> coins, int n, int sum)
    {
        // 2d dp array where n is the number of coin
        // denominations and sum is the target sum
        int[, ] dp = new int[n + 1, sum + 1];

        // Represents the base case where the target sum is
        // 0, and there is only one way to make change: by
        // not selecting any coin
        dp[0, 0] = 1;
        for (int i = 1; i <= n; i++) {
            for (int j = 0; j <= sum; j++) {
                // Add the number of ways to make change
                // without using the current coin
                dp[i, j] += dp[i - 1, j];

                if ((j - coins[i - 1]) >= 0) {
                    // Add the number of ways to make change
                    // using the current coin
                    dp[i, j] += dp[i, j - coins[i - 1]];
                }
            }
        }
        return dp[n, sum];
    }

    // Driver Code
    static void Main(string[] args)
    {
        List<int> coins = new List<int>{ 1, 2, 3 };
        int n = 3;
        int sum = 5;
        Console.WriteLine(Count(coins, n, sum));
    }
}
JavaScript
function count(coins, n, sum) {
    // Create a 2D array dp where n is the number of coin denominations
    // and sum is the target sum
    let dp = new Array(n + 1).fill(0).map(() => new Array(sum + 1).fill(0));

    // Set the base case where the target sum is 0, and there is only one way to make change
    // by not selecting any coin
    dp[0][0] = 1;

    for (let i = 1; i <= n; i++) {
        for (let j = 0; j <= sum; j++) {
            // Add the number of ways to make change without using the current coin
            dp[i][j] += dp[i - 1][j];

            if (j - coins[i - 1] >= 0) {
                // Add the number of ways to make change using the current coin
                dp[i][j] += dp[i][j - coins[i - 1]];
            }
        }
    }

    return dp[n][sum];
}

// Driver Code
let coins = [1, 2, 3];
let n = 3;
let sum = 5;
console.log(count(coins, n, sum));

Output
5

Time complexity : O(N*sum)
Auxiliary Space : O(N*sum)

Count Ways using Space Optimized DP

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.

Follow the below steps to Implement the idea:

  • 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:

C++
#include <bits/stdc++.h>

using namespace std;

// This code is 
int count(int coins[], int n, int sum)
{
    // table[i] will be storing the number of solutions for
    // value i. We need sum+1 rows as the dp is
    // constructed in bottom up manner using the base case
    // (sum = 0)
    int dp[sum + 1];

    // Initialize all table values as 0
    memset(dp, 0, sizeof(dp));

    // Base case (If given value is 0)
    dp[0] = 1;

    // Pick all coins one by one and update the table[]
    // values after the index greater than or equal to the
    // value of the picked coin
    for (int i = 0; i < n; i++)
        for (int j = coins[i]; j <= sum; j++)
            dp[j] += dp[j - coins[i]];
    return dp[sum];
}

// Driver Code
int main()
{
    int coins[] = { 1, 2, 3 };
    int n = sizeof(coins) / sizeof(coins[0]);
    int sum = 5;
    cout << count(coins, n, sum);
    return 0;
}
Java
/* Dynamic Programming Java implementation of Coin
Change problem */
import java.util.Arrays;

class CoinChange {
    static long count(int coins[], int n, int sum)
{
    // dp[i] will be storing the number of solutions for
    // value i. We need sum+1 rows as the dp is
    // constructed in bottom up manner using the base case
    // (sum = 0)
    int dp[] = new int[sum + 1];

    // Base case (If given value is 0)
    dp[0] = 1;

    // Pick all coins one by one and update the dp[]
    // values after the index greater than or equal to the
    // value of the picked coin
    for (int i = 0; i < n; i++)
        for (int j = coins[i]; j <= sum; j++)
            dp[j] += dp[j - coins[i]];

    return dp[sum];
}

    // Driver Function to test above function
    public static void main(String args[])
    {
        int coins[] = { 1, 2, 3 };
        int n = coins.length;
        int sum = 5;
        System.out.println(count(coins, n, sum));
    }
}
// This code is contributed by Pankaj Kumar
Python
# Dynamic Programming Python implementation of Coin
# Change problem


def count(coins, n, sum):

    # dp[i] will be storing the number of solutions for
    # value i. We need sum+1 rows as the dp is constructed
    # in bottom up manner using the base case (sum = 0)
    # Initialize all table values as 0
    dp = [0 for k in range(sum+1)]

    # Base case (If given value is 0)
    dp[0] = 1

    # Pick all coins one by one and update the dp[] values
    # after the index greater than or equal to the value of the
    # picked coin
    for i in range(0, n):
        for j in range(coins[i], sum+1):
            dp[j] += dp[j-coins[i]]

    return dp[sum]


# Driver program to test above function
coins = [1, 2, 3]
n = len(coins)
sum = 5
x = count(coins, n, sum)
print(x)

# This code is contributed by Afzal Ansari
C#
// Dynamic Programming C# implementation
// of Coin Change problem
using System;

class GFG {
    static int count(int[] coins, int n, int sum)
    {
        // dp[i] will be storing the
        // number of solutions for value i.
        // We need sum+1 rows as the dp
        // is constructed in bottom up manner
        // using the base case (sum = 0)
        int[] dp = new int[sum + 1];

        // Base case (If given value is 0)
        dp[0] = 1;

        // Pick all coins one by one and
        // update the dp[] values after
        // the index greater than or equal
        // to the value of the picked coin
        for (int i = 0; i < n; i++)
            for (int j = coins[i]; j <= sum; j++)
                dp[j] += dp[j - coins[i]];

        return dp[sum];
    }

    // Driver Code
    public static void Main()
    {
        int[] coins = { 1, 2, 3 };
        int n = coins.Length;
        int sum = 5;
        Console.Write(count(coins, n, sum));
    }
}

// This code is contributed by Raj
JavaScript
<script>
    // Dynamic Programming Javascript implementation
    // of Coin Change problem
    
    function count(coins, n, sum)
    {
        // dp[i] will be storing the
        // number of solutions for value i.
        // We need n+1 rows as the dp
        // is constructed in bottom up manner
        // using the base case (sum = 0)
        let dp = new Array(sum + 1);
        dp.fill(0);

        // Base case (If given value is 0)
        dp[0] = 1;

        // Pick all coins one by one and
        // update the dp[] values after
        // the index greater than or equal
        // to the value of the picked coin
        for(let i = 0; i < n; i++)
            for(let j = coins[i]; j <= sum; j++)
                dp[j] += dp[j - coins[i]];

        return dp[sum];
    }
    
    let coins = [1, 2, 3];
    let n = coins.length;
    let sum = 4;
    document.write(count(coins, n, sum));
</script>
PHP
<?php
function count_1( &$coins, $n, $sum )
{
    // table[i] will be storing the number 
    // of solutions for value i. We need sum+1 
    // rows as the table is constructed in
    // bottom up manner using the base case (sum = 0)
    $table = array_fill(0, $sum + 1, NULl);

    // Base case (If given value is 0)
    $table[0] = 1;

    // Pick all coins one by one and update 
    // the table[] values after the index 
    // greater than or equal to the value 
    // of the picked coin
    for($i = 0; $i < $n; $i++)
        for($j = $coins[$i]; $j <= $sum; $j++)
            $table[$j] += $table[$j - $coins[$i]];

    return $table[$sum];
}

// Driver Code
$coins = array(1, 2, 3);
$n = sizeof($coins);
$sum = 4;
$x = count_1($coins, $n, $sum);
echo $x;

// This code is contributed
// by ChitraNayal
?>

Output
5

Time complexity : O(N*sum)
Auxiliary Space : O(sum)

Related Articles

Coin Change – Minimum Coins to Make Sum
Understanding The Coin Change Problem With Dynamic Programming



Previous Article
Next Article

Similar Reads

Make a fair coin from a biased coin
You are given a function foo() that represents a biased coin. When foo() is called, it returns 0 with 60% probability, and 1 with 40% probability. Write a new function that returns 0 and 1 with a 50% probability each. Your function should use only foo(), no other library method. Solution: We know foo() returns 0 with 60% probability. How can we ens
6 min read
Coin Change - Minimum Coins to Make Sum
Given an array coins[] of size N and a target value sum, where coins[i] represents the coins of different denominations. You have an infinite supply of each of coins. The task is to find minimum number of coins required to make the given value sum. If it's not possible to make a change, print -1. Examples: Input: coins[] = {25, 10, 5}, sum = 30Outp
15+ min read
Decision Trees - Fake (Counterfeit) Coin Puzzle (12 Coin Puzzle)
Let us solve the classic "fake coin" puzzle using decision trees. There are the two different variants of the puzzle given below. I am providing description of both the puzzles below, try to solve on your own, assume N = 8. Easy: Given a two pan fair balance and N identically looking coins, out of which only one coin is lighter (or heavier). To fig
12 min read
Count ways to distribute exactly one coin to each worker
Given two arrays coins[] and salaries[] where coins[i] represents the value of ith coin and salaries[j] represents the minimum value of the coin that jth worker will accept. The task is to compute the number of ways to distribute exactly one coin to each worker. Since the answer can be large, print it modulo 109 + 7.Examples: Input: coins[] = {1, 2
6 min read
Coin Change | BFS Approach
Given an integer X and an array arr[] of length N consisting of positive integers, the task is to pick minimum number of integers from the array such that they sum up to N. Any number can be chosen infinite number of times. If no answer exists then print -1.Examples: Input: X = 7, arr[] = {3, 5, 4} Output: 2 The minimum number elements will be 2 as
6 min read
Coin change problem with limited coins
Given three integers n, k, target, and an array of coins[] of size n. Find if it is possible to make a change of target cents by using an infinite supply of each coin but the total number of coins used must be exactly equal to k. Examples: Input: n = 5, k = 3, target = 11, coins = {1, 10, 5, 8, 6}Output: 1Explanation: 2 coins of 5 and 1 coin of 1 c
12 min read
Count ways to replace '?' in a Binary String to make the count of 0s and 1s same as that of another string
Given two binary strings S1 and S2 of size N and M respectively such that the string S2 also contains the character '?', the task is to find the number of ways to replace '?' in the string S2 such that the count of 0s and 1s in the string S2 is the same as in the string S1. Examples: Input: S1 = "1010", S2 = "10??"Output: 2Explanation:Following are
11 min read
Count of ways to make Array sum even by removing only one element
Given an array arr[] positive integers, the task is to find the number of ways to convert the array sum even if we are allowed to remove only one element.Examples: Input: arr[] = { 1, 3, 3, 2 } Output: 3 Explanation: 1. Remove 1, then sum is 3 + 3 + 2 = 8. 2. Remove 3, then sum is 1 + 3 + 2 = 6. 3. Remove 3, then sum is 1 + 3 + 2 = 6.Input: arr[] =
5 min read
Count ways to make sum of odd and even indexed elements equal by removing an array element
Given an array, arr[] of size N, the task is to find the count of array indices such that removing an element from these indices makes the sum of even-indexed and odd-indexed array elements equal. Examples: Input: arr[] = { 2, 1, 6, 4 } Output: 1 Explanation: Removing arr[1] from the array modifies arr[] to { 2, 6, 4 } such that, arr[0] + arr[2] =
15 min read
Count of ways to make sum of all columns 0 by changing any number of 1s in Matrix to -1
Given a matrix of size N x M initially filled with 1, the task is to find the number of ways to make the sum of all columns 0 by changing any number of 1's to -1. Note: As the answer can be very large print it modulo 1e9 + 7 Examples: Input: N = 2, M = 1Output: 2Explanation: Upper example consist 2 rows and 1 column and all cells are filled with 1.
6 min read
Count of ways to choose 4 unique position elements one from each Array to make sum at most K
Given four arrays A[], B[], C[], D[] and an integer K. The task is to find the number of combinations of four unique indices p, q, r, s such that A[p] + B[q] + C[r] + D[s] â‰Ī K. Examples: Input: A = {2, 3}, B = {5, 2}, C = {0}, D = {1, 2}, K = 6Output: 3Explanation: The following are the required combinations:{2, 2, 0, 1}, {2, 2, 0, 2}, {3, 2, 0, 1}
13 min read
Count of total Heads and Tails after N flips in a coin
Given character C and an integer N representing N number of coins in C position where C can be either head or tail. We can flip the coins N times, wherein the ith round the player will flip the face of all the coins whose number is less than or equal to i. The task is to determine the total number of head and tail after flipping N possible times. E
6 min read
CSES Solutions - Missing Coin Sum
You have N coins with positive integer values. What is the smallest sum you cannot create using a subset of the coins? Examples: Input: N = 5, coins[] = {2, 9, 1, 2, 7}Output: 6Explanation: Sum = 1, we can take the coin with value 1.Sum = 2, we can take the coin with value 2.Sum = 3, we can take coins with value 1 and 2.Sum = 4, we can take coins w
6 min read
Count ways to change direction of edges such that graph becomes acyclic
Given a directed and unweighted graph consisting of N vertices and an array arr[] where ith vertex has a directed edge to arr[i]. The task is to find the number of ways to change the direction of edges such that the given graph is acyclic. Examples: Input: N = 3, arr[] = {2, 3, 1} The directed graph form by the given information is: Output: 6 Expla
12 min read
Count ways to divide C in two parts and add to A and B to make A strictly greater than B
Given three integers A, B and C, the task is to count the number of ways to divide C into two parts and add to A and B such that A is strictly greater than B. Examples: Input: A = 5, B = 3, C = 4 Output: 3 The possible values of A and B after dividing C are: A = 7, B = 5 where C is divided into 2 and 2. A = 8, B = 4 where C is divided into 3 and 1.
5 min read
Count ways to make the number formed by K concatenations of a numeric string divisible by 5
Given a string S consisting of N digits and an integer K, the task is to count the number of ways to remove digits from the number formed by the concatenating the string S, K number of times, such that the resulting string is divisible by 5. Since count can be very large, so print it to modulo 109 + 7. Examples: Input: S = 1256, K = 1Output: 4Expla
8 min read
Count ways to make Bitwise XOR of odd and even indexed elements equal by removing an array element
Given an array arr[] of length N, the task is to find the count of array indices such that removing an element from these indices makes the Bitwise xor of odd-indexed elements and even-indexed (1-based indexing) elements are equal. Examples: Input: arr[] = {1, 0, 1, 0, 1}, N = 5Output: 3Explanation: Removing an element from index 3 modifies arr[] t
10 min read
Count ways to make product of array elements even by replacements
Given an array arr[] consisting of N integers, the task is to count the number of ways to make the product of array elements even by replacing array elements any number of times. Since the count can be very large, print the count modulo 109+7. Examples: Input: arr[] = {1, 3}Output: 3Explanation: Operation 1: Replacing arr[0] by 2. Therefore, arr[]
4 min read
Count ways to make given Subarray strictly increasing by replacing one element for Q queries
Given a strictly increasing array A[] of size N, an integer K and Q queries of type [L, R], the task is to count the number of ways such that the subarray from L to R remains strictly increasing when only one replacement is performed and all the elements will be in the range [1, K]. Examples: Input: A[] = {1, 2, 4, 5}, K = 5, Q = 2, Queries[][] = {
12 min read
Coin game of two corners (Greedy Approach)
Consider a two-player coin game where each player gets turned one by one. There is a row of even a number of coins, and a player on his/her turn can pick a coin from any of the two corners of the row. The player that collects coins with more value wins the game. Develop a strategy for the player making the first turn, such that he/she never loses t
9 min read
Probability of getting two consecutive heads after choosing a random coin among two different types of coins
Given two coins which have probability of getting heads p% and q% respectively, the task is to determine the probability of getting two consecutive heads after choosing random coins among the given coins.Examples: Input: p = 33, q = 66 Output: 0.550000000000000Input: p = 33, q = 66 Output: 0.550000000000000 Approach: Since both the coins are not id
5 min read
Predict the winner in Coin Game
There are two players P1 and P2 and two piles of coins consisting of M and N coins respectively. At each turn, a player can choose only one of the piles out of these and discard the other one. This discarded pile cannot be used further in the game. The pile player chooses is further divided into two piles of non-zero parts. The player who cannot di
4 min read
Find the player who will win the Coin game
Given N coins, the task is to find who win the coin game.Coin game is a game in which each player picks coins from the given N coins in such a way that he can pick coins ranging from 1 to 5 coins in one turn and the game continues for both the players. The player who picks the last coin loses the game.Examples: Input: N = 4 Output: First Player Exp
4 min read
Probability of not getting two consecutive heads together in N tosses of coin
Given a fair coin that is tossed N times, the task is to determine the probability such that no two heads occur consecutively. Examples: Input: N = 2 Output: 0.75 Explanation: When the coin is tossed 2 times, the possible outcomes are {TH, HT, TT, HH}. Since in 3 out of 4 outcomes, heads don't occur together. Therefore, the required probability is
8 min read
Probability of getting K heads in N coin tosses
Given two integers N and R. The task is to calculate the probability of getting exactly r heads in n successive tosses. A fair coin has an equal probability of landing a head or a tail on each toss. Examples: Input : N = 1, R = 1 Output : 0.500000 Input : N = 4, R = 3 Output : 0.250000 Approach Probability of getting K heads in N coin tosses can be
4 min read
Minimum moves taken to move coin of each cell to any one cell of Matrix
Given an odd number N which represents a grid of size N x N which is initially filled by coins, the task is to find the minimum number of moves required for all the coins to move to any cell of the grid such that in each step, some arbitrary coin in the middle of the grid can move to any of the surrounding eight cells. Examples: Input: N = 3 Output
6 min read
Philaland Coin | TCS Mockvita 2020
Problem Description The problem solvers have found a new Island for coding and named it as Philaland. These smart people were given a task to make purchase of items at the Island easier by distributing various coins with different value. Manish has come up with a solution that if we make coins category starting from $1 till the maximum price of ite
4 min read
Check if two piles of coins can be emptied by repeatedly removing 2 coins from a pile and 1 coin from the other
Given two piles of coins consisting of N and M coins, the task is to check if both the piles can be emptied simultaneously by repeatedly removing 2 coins from one pile and 1 coin from the other pile. If both the piles can be made empty, then print "Yes". Otherwise, print "No". Examples: Input: N = 1, M = 2 Output: Yes Explanation: Remove 1 coin fro
6 min read
Maximum coin in minimum time by skipping K obstacles along path in Matrix
Given a 2D matrix, where '*' represents an obstacle and the rest all represent coins in the grid. It is also given that you are currently on grid[i1][ j1] and want to reach grid[i2][j2] by skipping at most K obstacles in the path, the task is to collect the maximum coin while reaching grid[i2][j2] in a minimum amount of time. Note: Only movements i
14 min read
Frobenius coin problem
Given two coins of denominations "X" and "Y" respectively, find the largest amount that cannot be obtained using these two coins (assuming an infinite supply of coins) followed by the total number of such non-obtainable amounts, if no such value exists print "NA". Examples : Input : X=2, Y=5 Output: Largest amount = 3 Total count = 2 We cannot repr
7 min read