Generate a combination of minimum coins that sums to a given value
Last Updated :
15 Jul, 2025
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 results
int dp[MAX + 1];
// List to store the result
list<int> denomination;
// Function to find the minimum number of
// coins to make the sum equals to X
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_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 X
void 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 X
void 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 code
int 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 approach
import java.util.*;
class GFG{
static final int MAX = 100000;
// dp array to memoize the results
static int []dp = new int[MAX + 1];
// List to store the result
static List<Integer> denomination =
new LinkedList<Integer>();
// Function to find the minimum
// number of coins to make the
// sum equals to X
static 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 X
static 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 X
static 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 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
countMinCoinsUtil(X, arr, N);
}
}
// This code is contributed by Rajput-Ji
Python3
# Python3 program for the above approach
import sys
MAX = 100000
# dp array to memoize the results
dp = [-1] * (MAX + 1)
# List to store the result
denomination = []
# Function to find the minimum number of
# coins to make the sum equals to X
def 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 X
def 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 X
def 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 code
if __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 approach
using System;
using System.Collections.Generic;
class GFG{
static readonly int MAX = 100000;
// dp array to memoize the results
static int []dp = new int[MAX + 1];
// List to store the result
static List<int> denomination =
new List<int>();
// Function to find the minimum
// number of coins to make the
// sum equals to X
static 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 X
static 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 X
static 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 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
countMinCoinsUtil(X, arr, N);
}
}
// This code is contributed by shikhasingrajput
JavaScript
<script>
// Javascript program for the above approach
var MAX = 100000;
// dp array to memoize the results
var dp = Array(MAX+1);
// List to store the result
var denomination = [];
// Function to find the minimum number of
// coins to make the sum equals to X
function 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 X
function 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 X
function 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 code
var X = 21;
// Set of possible denominations
var arr = [2, 3, 4, 5];
var N = arr.length;
// Function Call
countMinCoinsUtil(X, arr, N);
</script>
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 X
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[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 code
int 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 X
def 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 code
if __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 X
function 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 code
const X = 21;
// Set of possible denominations
const arr = [2, 3, 4, 5];
const N = arr.length;
// Function Call
countMinCoins(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)
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem