Given an array arr[] of size N representing the available denominations and an integer X. The task is to find any combination of the minimum number of coins of the available denominations such that the sum of the coins is X. If the given sum cannot be obtained by the available denominations, print -1.
Examples:
Input: X = 21, arr[] = {2, 3, 4, 5}
Output: 2 4 5 5 5
Explanation:
One possible solution is {2, 4, 5, 5, 5} where 2 + 4 + 5 + 5 + 5 = 21.Â
Another possible solution is {3, 3, 5, 5, 5}.Input: X = 1, arr[] = {2, 4, 6, 9}
Output: -1
Explanation:
All coins are greater than 1. Hence, no solution exist.
Naive Approach: The simplest approach is to try all possible combinations of given denominations such that in each combination, the sum of coins is equal to X. From these combinations, choose the one having the minimum number of coins and print it. If the sum any combinations is not equal to X, print -1.Â
Time Complexity: O(XN)
Auxiliary Space: O(N)
Efficient Approach: The above approach can be optimized using Dynamic Programming to find the minimum number of coins. While finding the minimum number of coins, backtracking can be used to track the coins needed to make their sum equals to X. Follow the below steps to solve the problem:
- Initialize an auxiliary array dp[], where dp[i] will store the minimum number of coins needed to make sum equals to i.
- Find the minimum number of coins needed to make their sum equals to X using the approach discussed in this article.
- After finding the minimum number of coins use the Backtracking Technique to track down the coins used, to make the sum equals to X.
- In backtracking, traverse the array and choose a coin which is smaller than the current sum such that dp[current_sum] equals to dp[current_sum – chosen_coin]+1. Store the chosen coin in an array.
- After completing the above step, backtrack again by passing the current sum as (current sum – chosen coin value).
- After finding the solution, print the array of chosen coins.
Below is the implementation of the above approach:
C++
// C++ program for the above approachÂ
#include <bits/stdc++.h>using namespace std;#define MAX 100000Â
// dp array to memoize the resultsint dp[MAX + 1];Â
// List to store the resultlist<int> denomination;Â
// Function to find the minimum number of// coins to make the sum equals to Xint countMinCoins(int n, int C[], int m){    // Base case    if (n == 0) {        dp[0] = 0;        return 0;    }Â
    // If previously computed    // subproblem occurred    if (dp[n] != -1)        return dp[n];Â
    // Initialize result    int ret = INT_MAX;Â
    // Try every coin that has smaller    // value than n    for (int i = 0; i < m; i++) {Â
        if (C[i] <= n) {Â
            int x                = countMinCoins(n - C[i],                                C, m);Â
            // Check for INT_MAX to avoid            // overflow and see if result            // can be minimized            if (x != INT_MAX)                ret = min(ret, 1 + x);        }    }Â
    // Memoizing value of current state    dp[n] = ret;    return ret;}Â
// Function to find the possible// combination of coins to make// the sum equal to Xvoid findSolution(int n, int C[], int m){    // Base Case    if (n == 0) {Â
        // Print Solutions        for (auto it : denomination) {            cout << it << ' ';        }Â
        return;    }Â
    for (int i = 0; i < m; i++) {Â
        // Try every coin that has        // value smaller than n        if (n - C[i] >= 0            and dp[n - C[i]] + 1                    == dp[n]) {Â
            // Add current denominations            denomination.push_back(C[i]);Â
            // Backtrack            findSolution(n - C[i], C, m);            break;        }    }}Â
// Function to find the minimum// combinations of coins for value Xvoid countMinCoinsUtil(int X, int C[],                       int N){Â
    // Initialize dp with -1    memset(dp, -1, sizeof(dp));Â
    // Min coins    int isPossible        = countMinCoins(X, C,                        N);Â
    // If no solution exists    if (isPossible == INT_MAX) {        cout << "-1";    }Â
    // Backtrack to find the solution    else {        findSolution(X, C, N);    }}Â
// Driver codeint main(){Â Â Â Â int X = 21;Â
    // Set of possible denominations    int arr[] = { 2, 3, 4, 5 };Â
    int N = sizeof(arr) / sizeof(arr[0]);Â
    // Function Call    countMinCoinsUtil(X, arr, N);Â
    return 0;} |
Java
// Java program for // the above approachimport java.util.*;class GFG{Â Â Â static final int MAX = 100000;Â
// dp array to memoize the resultsstatic int []dp = new int[MAX + 1];Â
// List to store the resultstatic List<Integer> denomination = Â Â Â Â Â Â Â Â Â Â Â Â new LinkedList<Integer>();Â
// Function to find the minimum // number of coins to make the // sum equals to Xstatic int countMinCoins(int n,                          int C[], int m){  // Base case  if (n == 0)   {    dp[0] = 0;    return 0;  }Â
  // If previously computed  // subproblem occurred  if (dp[n] != -1)    return dp[n];Â
  // Initialize result  int ret = Integer.MAX_VALUE;Â
  // Try every coin that has smaller  // value than n  for (int i = 0; i < m; i++)   {    if (C[i] <= n)     {      int x = countMinCoins(n - C[i],                            C, m);Â
      // Check for Integer.MAX_VALUE to avoid      // overflow and see if result      // can be minimized      if (x != Integer.MAX_VALUE)        ret = Math.min(ret, 1 + x);    }  }Â
  // Memoizing value of current state  dp[n] = ret;  return ret;}Â
// Function to find the possible// combination of coins to make// the sum equal to Xstatic void findSolution(int n,                          int C[], int m){  // Base Case  if (n == 0)   {    // Print Solutions    for (int it : denomination)     {      System.out.print(it + " ");    }    return;  }Â
  for (int i = 0; i < m; i++)   {    // Try every coin that has    // value smaller than n    if (n - C[i] >= 0 &&         dp[n - C[i]] + 1 ==         dp[n])     {      // Add current denominations      denomination.add(C[i]);Â
      // Backtrack      findSolution(n - C[i], C, m);      break;    }  }}Â
// Function to find the minimum// combinations of coins for value Xstatic void countMinCoinsUtil(int X, Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â int C[], int N){Â Â // Initialize dp with -1Â Â for (int i = 0; i < dp.length; i++)Â Â Â Â dp[i] = -1;Â
  // Min coins  int isPossible = countMinCoins(X, C, N);Â
  // If no solution exists  if (isPossible == Integer.MAX_VALUE)   {    System.out.print("-1");  }Â
  // Backtrack to find the solution  else  {    findSolution(X, C, N);  }}Â
// Driver codepublic static void main(String[] args){Â Â int X = 21;Â
  // Set of possible denominations  int arr[] = {2, 3, 4, 5};Â
  int N = arr.length;Â
  // Function Call  countMinCoinsUtil(X, arr, N);}}Â
// This code is contributed by Rajput-Ji |
Python3
# Python3 program for the above approachimport sysÂ
MAX = 100000Â
# dp array to memoize the resultsdp = [-1] * (MAX + 1)Â
# List to store the resultdenomination = []Â
# Function to find the minimum number of# coins to make the sum equals to Xdef countMinCoins(n, C, m):         # Base case    if (n == 0):        dp[0] = 0        return 0Â
    # If previously computed    # subproblem occurred    if (dp[n] != -1):        return dp[n]Â
    # Initialize result    ret = sys.maxsizeÂ
    # Try every coin that has smaller    # value than n    for i in range(m):        if (C[i] <= n):            x = countMinCoins(n - C[i], C, m)Â
            # Check for INT_MAX to avoid            # overflow and see if result            # can be minimized            if (x != sys.maxsize):                ret = min(ret, 1 + x)Â
    # Memoizing value of current state    dp[n] = ret    return retÂ
# Function to find the possible# combination of coins to make# the sum equal to Xdef findSolution(n, C, m):         # Base Case    if (n == 0):Â
        # Print Solutions        for it in denomination:            print(it, end = " ")Â
        returnÂ
    for i in range(m):Â
        # Try every coin that has        # value smaller than n        if (n - C[i] >= 0 and         dp[n - C[i]] + 1 == dp[n]):Â
            # Add current denominations            denomination.append(C[i])Â
            # Backtrack            findSolution(n - C[i], C, m)            breakÂ
# Function to find the minimum# combinations of coins for value Xdef countMinCoinsUtil(X, C,N):Â
    # Initialize dp with -1    # memset(dp, -1, sizeof(dp))Â
    # Min coins    isPossible = countMinCoins(X, C,N)Â
    # If no solution exists    if (isPossible == sys.maxsize):        print("-1")Â
    # Backtrack to find the solution    else:        findSolution(X, C, N)Â
# Driver codeif __name__ == '__main__':Â Â Â Â Â Â Â Â Â X = 21Â
    # Set of possible denominations    arr = [ 2, 3, 4, 5 ]Â
    N = len(arr)Â
    # Function call    countMinCoinsUtil(X, arr, N)Â
# This code is contributed by mohit kumar 29 |
C#
// C# program for // the above approachusing System;using System.Collections.Generic;class GFG{Â Â Â static readonly int MAX = 100000;Â
// dp array to memoize the resultsstatic int []dp = new int[MAX + 1];Â
// List to store the resultstatic List<int> denomination = Â Â Â Â Â Â Â Â Â Â Â Â new List<int>();Â
// Function to find the minimum // number of coins to make the // sum equals to Xstatic int countMinCoins(int n,                          int []C,                          int m){  // Base case  if (n == 0)   {    dp[0] = 0;    return 0;  }Â
  // If previously computed  // subproblem occurred  if (dp[n] != -1)    return dp[n];Â
  // Initialize result  int ret = int.MaxValue;Â
  // Try every coin that has smaller  // value than n  for (int i = 0; i < m; i++)   {    if (C[i] <= n)     {      int x = countMinCoins(n - C[i],                            C, m);Â
      // Check for int.MaxValue to avoid      // overflow and see if result      // can be minimized      if (x != int.MaxValue)        ret = Math.Min(ret, 1 + x);    }  }Â
  // Memoizing value of current state  dp[n] = ret;  return ret;}Â
// Function to find the possible// combination of coins to make// the sum equal to Xstatic void findSolution(int n,                          int []C,                          int m){  // Base Case  if (n == 0)   {    // Print Solutions    foreach (int it in denomination)     {      Console.Write(it + " ");    }    return;  }Â
  for (int i = 0; i < m; i++)   {    // Try every coin that has    // value smaller than n    if (n - C[i] >= 0 &&         dp[n - C[i]] + 1 ==         dp[n])     {      // Add current denominations      denomination.Add(C[i]);Â
      // Backtrack      findSolution(n - C[i], C, m);      break;    }  }}Â
// Function to find the minimum// combinations of coins for value Xstatic void countMinCoinsUtil(int X, Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â int []C, Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â int N){Â Â // Initialize dp with -1Â Â for (int i = 0; i < dp.Length; i++)Â Â Â Â dp[i] = -1;Â
  // Min coins  int isPossible = countMinCoins(X, C, N);Â
  // If no solution exists  if (isPossible == int.MaxValue)   {    Console.Write("-1");  }Â
  // Backtrack to find the solution  else  {    findSolution(X, C, N);  }}Â
// Driver codepublic static void Main(String[] args){Â Â int X = 21;Â
  // Set of possible denominations  int []arr = {2, 3, 4, 5};Â
  int N = arr.Length;Â
  // Function Call  countMinCoinsUtil(X, arr, N);}}Â
// This code is contributed by shikhasingrajput |
Javascript
<script>Â
// Javascript program for the above approachvar MAX = 100000;Â
// dp array to memoize the resultsvar dp = Array(MAX+1);Â
// List to store the resultvar denomination = [];Â
// Function to find the minimum number of// coins to make the sum equals to Xfunction countMinCoins(n, C, m){    // Base case    if (n == 0) {        dp[0] = 0;        return 0;    }Â
    // If previously computed    // subproblem occurred    if (dp[n] != -1)        return dp[n];Â
    // Initialize result    var ret = 1000000000;Â
    // Try every coin that has smaller    // value than n    for (var i = 0; i < m; i++) {Â
        if (C[i] <= n) {Â
            var x                = countMinCoins(n - C[i],                                C, m);Â
            // Check for INT_MAX to avoid            // overflow and see if result            // can be minimized            if (x != 1000000000)                ret = Math.min(ret, 1 + x);        }    }Â
    // Memoizing value of current state    dp[n] = ret;    return ret;}Â
// Function to find the possible// combination of coins to make// the sum equal to Xfunction findSolution(n, C, m){    // Base Case    if (n == 0) {Â
        denomination.forEach(it => {                         document.write( it + ' ');        });Â
        return;    }Â
    for (var i = 0; i < m; i++) {Â
        // Try every coin that has        // value smaller than n        if (n - C[i] >= 0            && dp[n - C[i]] + 1                    == dp[n]) {Â
            // Add current denominations            denomination.push(C[i]);Â
            // Backtrack            findSolution(n - C[i], C, m);            break;        }    }}Â
// Function to find the minimum// combinations of coins for value Xfunction countMinCoinsUtil(X, C, N){Â
    // Initialize dp with -1    dp = Array(MAX+1).fill(-1);Â
    // Min coins    var isPossible        = countMinCoins(X, C,                        N);Â
    // If no solution exists    if (isPossible == 1000000000) {        document.write( "-1");    }Â
    // Backtrack to find the solution    else {        findSolution(X, C, N);    }}Â
// Driver codevar X = 21;// Set of possible denominationsvar arr = [2, 3, 4, 5];var N = arr.length;// Function CallcountMinCoinsUtil(X, arr, N);Â
</script> |
2 4 5 5 5
Time Complexity: O(N*X), where N is the length of the given array and X is the given integer.
Auxiliary Space: O(N)
Efficient approach : Using DP Tabulation method ( Iterative approach )
The approach to solve this problem is same but DP tabulation(bottom-up) method is better then Dp + memoization(top-down) because memoization method needs extra stack space of recursion calls.
Steps to solve this problem :
- Create a array DP to store the solution of the subproblems and initialize it with INT_MAX.
- Initialize the array DP with base case i.e. dp[0] = 0 .
- Now Iterate over subproblems to get the value of current problem form previous computation of subproblems stored in DP
- Return the final solution stored in dp[X].
Implementation :
C++
// C++ program for above approach#include <bits/stdc++.h>using namespace std;#define MAX 100000Â
// Function to find the minimum number of// coins to make the sum equals to Xint countMinCoins(int X, int C[], int N){Â Â Â Â // dp array to store the minimum number of coins for each value from 0 to XÂ Â Â Â int dp[X + 1];Â
    // Initialize dp array    dp[0] = 0;    for (int i = 1; i <= X; i++) {        dp[i] = INT_MAX;    }Â
    // Loop through all values from 1 to X and compute the minimum number of coins    for (int i = 1; i <= X; i++) {        for (int j = 0; j < N; j++) {            if (C[j] <= i && dp[i - C[j]] != INT_MAX) {                dp[i] = min(dp[i], 1 + dp[i - C[j]]);            }        }    }Â
    // If no solution exists    if (dp[X] == INT_MAX) {        cout << "-1";        return -1;    }Â
    // Print the solution    int i = X;    while (i > 0) {        for (int j = 0; j < N; j++) {            if (i >= C[j] && dp[i - C[j]] == dp[i] - 1) {                cout << C[j] << " ";                i -= C[j];                break;            }        }    }Â
    return dp[X];}Â
// Driver codeint main(){Â Â Â Â int X = 21;Â
    // Set of possible denominations    int arr[] = { 2, 3, 4, 5 };Â
    int N = sizeof(arr) / sizeof(arr[0]);Â
    // Function Call    countMinCoins(X, arr, N);Â
    return 0;}// this code is contributed by bhardwajji |
Java
import java.util.*;Â
public class Main {Â
    // Function to find the minimum number of coins to make the sum equals to X    public static int countMinCoins(int X, int[] C, int N) {        // dp array to store the minimum number of coins for each value from 0 to X        int[] dp = new int[X + 1];Â
        // Initialize dp array        dp[0] = 0;        for (int i = 1; i <= X; i++) {            dp[i] = Integer.MAX_VALUE;        }Â
        // Loop through all values from 1 to X and compute       // the minimum number of coins        for (int i = 1; i <= X; i++) {            for (int j = 0; j < N; j++) {                if (C[j] <= i && dp[i - C[j]] != Integer.MAX_VALUE) {                    dp[i] = Math.min(dp[i], 1 + dp[i - C[j]]);                }            }        }Â
        // If no solution exists        if (dp[X] == Integer.MAX_VALUE) {            System.out.println("-1");            return -1;        }Â
        // Print the solution        int i = X;        while (i > 0) {            for (int j = 0; j < N; j++) {                if (i >= C[j] && dp[i - C[j]] == dp[i] - 1) {                    System.out.print(C[j] + " ");                    i -= C[j];                    break;                }            }        }        System.out.println();Â
        return dp[X];    }Â
    // Driver code    public static void main(String[] args) {        int X = 21;Â
        // Set of possible denominations        int[] arr = { 2, 3, 4, 5 };Â
        int N = arr.length;Â
        // Function Call        countMinCoins(X, arr, N);    }} |
Python3
import sysÂ
# Function to find the minimum number of coins to make the sum equals to Xdef countMinCoins(X, C, N):Â Â Â Â # dp array to store the minimum number of coins for each value from 0 to XÂ Â Â Â dp = [sys.maxsize] * (X + 1)Â
    # Initialize dp array    dp[0] = 0Â
    # Loop through all values from 1 to X and compute the minimum number of coins    for i in range(1, X + 1):        for j in range(N):            if C[j] <= i and dp[i - C[j]] != sys.maxsize:                dp[i] = min(dp[i], 1 + dp[i - C[j]])Â
    # If no solution exists    if dp[X] == sys.maxsize:        print("-1")        return -1Â
    # Print the solution    i = X    while i > 0:        for j in range(N):            if i >= C[j] and dp[i - C[j]] == dp[i] - 1:                print(C[j], end=" ")                i -= C[j]                breakÂ
    return dp[X]Â
# Driver codeif __name__ == "__main__":Â Â Â Â X = 21Â
    # Set of possible denominations    arr = [2, 3, 4, 5]Â
    N = len(arr)Â
    # Function Call    countMinCoins(X, arr, N) |
C#
using System;Â
class Program{Â Â Â Â // Function to find the minimum number of coins to make the sum equals to XÂ Â Â Â static int CountMinCoins(int X, int[] C, int N)Â Â Â Â {Â Â Â Â Â Â Â Â // dp array to store the minimum number of coins for each value from 0 to XÂ Â Â Â Â Â Â Â int[] dp = new int[X + 1];Â
        // Initialize dp array        dp[0] = 0;        for (int i = 1; i <= X; i++)        {            dp[i] = int.MaxValue;        }Â
        // Loop through all values from 1 to X and compute the minimum number of coins        for (int i = 1; i <= X; i++)        {            for (int j = 0; j < N; j++)            {                if (C[j] <= i && dp[i - C[j]] != int.MaxValue)                {                    dp[i] = Math.Min(dp[i], 1 + dp[i - C[j]]);                }            }        }Â
        // If no solution exists        if (dp[X] == int.MaxValue)        {            Console.WriteLine("-1");            return -1;        }Â
        // Print the solution        int k = X;        while (k > 0)        {            for (int j = 0; j < N; j++)            {                if (k >= C[j] && dp[k - C[j]] == dp[k] - 1)                {                    Console.Write(C[j] + " ");                    k -= C[j];                    break;                }            }        }Â
        return dp[X];    }Â
    // Driver code    static void Main(string[] args)    {        int X = 21;Â
        // Set of possible denominations        int[] arr = { 2, 3, 4, 5 };Â
        int N = arr.Length;Â
        // Function Call        CountMinCoins(X, arr, N);    }} |
Javascript
// javascript code addition Â
// Function to find the minimum number of coins to make the sum equals to Xfunction countMinCoins(X, C, N) {Â
  // dp array to store the minimum number of coins for each value from 0 to X  const dp = new Array(X + 1).fill(Infinity);Â
  // Initialize dp array  dp[0] = 0;Â
  // Loop through all values from 1 to X and compute the minimum number of coins  for (let i = 1; i <= X; i++) {    for (let j = 0; j < N; j++) {      if (C[j] <= i && dp[i - C[j]] !== Infinity) {        dp[i] = Math.min(dp[i], 1 + dp[i - C[j]]);      }    }  }Â
  // If no solution exists  if (dp[X] === Infinity) {    console.log("-1");    return -1;  }Â
  // Print the solution  let i = X;  const result = [];  while (i > 0) {    for (let j = 0; j < N; j++) {      if (i >= C[j] && dp[i - C[j]] === dp[i] - 1) {        result.push(C[j]);        i -= C[j];        break;      }    }  }Â
  console.log(result.join(' '));Â
  return dp[X];}Â
// Driver codeconst X = 21;Â
// Set of possible denominationsconst arr = [2, 3, 4, 5];Â
const N = arr.length;Â
// Function CallcountMinCoins(X, arr, N);Â
// The code is contributed by Nidhi goel. |
Output
2 4 5 5 5
Time Complexity: O(N*X), where N is the length of the given array and X is the given integer.
Auxiliary Space: O(X)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!
