![]() |
VOOZH | about |
Given an arrayarr[] of size N representing the available denominations and an integerX. 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:
Below is the implementation of the above approach:
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 :
Implementation :
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)