VOOZH about

URL: https://www.geeksforgeeks.org/dsa/cses-solutions-money-sums/

⇱ CSES Solutions - Money Sums - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

CSES Solutions - Money Sums

Last Updated : 23 Jul, 2025

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:

  • Maintain a boolean dp[][] array such that dp[i][j] = true if it is possible to make sum j using first i coins.
  • Initialize a variable sum to store the sum of all coins.
  • Iterate over each coin from i = 1 to N
    • Iterate over each sum j = 0 to j <= sum,
      • If dp[i - 1][j] = true, dp[i][j] = true
      • Else if dp[i - 1][j - coins[i]] = true,
      • Else dp[i][j] = false
  • Store the sums j from 1 to sum which are possible to construct, that is dp[N][j] = true
  • Print the number of possible sums along with all the possible sums.

Below is the implementation of the algorithm:


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

Comment
Article Tags:
Article Tags: