![]() |
VOOZH | about |
You have N coins with certain values. Your task is to find all money sums you can create using these coins.
Examples:
Input: N = 4, coins[] = {4, 2, 5, 2}
Output:
9
2 4 5 6 7 8 9 11 13
Explanation:
- To create sum = 2, we can use the coin with value = 2.
- To create sum = 4, we can use both the coins with value = 2.
- To create sum = 5, we can use the coin with value = 5.
- To create sum = 6, we can use coin with value = 2 and coin with value = 4.
- To create sum = 7, we can use coin with value = 2 and coin with value = 5.
- To create sum = 8, we can use both the coins with value = 2 and another coin with value = 4.
- To create sum = 9, we can use coin with value = 4 and coin with value = 5.
- To create sum = 11, we can use coin with value = 2, coin with value = 4 and coin with value = 5.
- To create sum = 13, we can use both the coins with value = 2, coin with value = 4 and coin with value = 5.
Input: N = 10, coins[] = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1}
Output:
10
1 2 3 4 5 6 7 8 9 10
Approach: To solve the problem, follow the below idea:
The problem can be solved using Dynamic Programming. We'll define dp[][], such that dp[i][j] = true if it is possible to make a sum of j with i coins and dp[i][j] = false if it is impossible to make a sum of j with i coins. Iterate through all the coins i and possible sums j:
- If dp[i - 1][j] = true, then dp[i][j] = true because if it is possible to make a sum of j with (i-1) coins, then we can make the same sum with i coins as well.
- Else if dp[i - 1][j - coins[i]] = true, then dp[i][j] = true because if it is possible to make a sum of (j - coins[i]) with i - 1 coins, then we can make sum j by using the ith coin.
For all values of j, dp[N][j] will store whether it is possible to create sum j or not.
Step-by-step algorithm:
Below is the implementation of the algorithm:
9 2 4 5 6 7 8 9 11 13
Time Complexity: O(N * X), where N is the number of coins and X is the sum of values of all coins
Auxiliary Space: O(N * X)