VOOZH about

URL: https://www.geeksforgeeks.org/dsa/cses-solutions-coin-combinations-i/

⇱ CSES Solutions - Coin Combinations I - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

CSES Solutions - Coin Combinations I

Last Updated : 23 Jul, 2025

Consider a money system consisting of N coins. Each coin has a positive integer value. Your task is to calculate the number of distinct ways you can produce a money sum X using the available coins.

Examples:

Input: N = 3, X = 9, coins[] = {2, 3, 5}
Output: 8
Explanation: There are 8 number of ways to make sum = 9.

  • {2, 2, 5} = 2 + 2 + 5 = 9
  • {2, 5, 2} = 2 + 5 + 2 = 9
  • {5, 2, 2} = 5 + 2 + 2 = 9
  • {3, 3, 3} = 3 + 3 + 3 = 9
  • {2, 2, 2, 3} = 2 + 2 + 2 + 3 = 9
  • {2, 2, 3, 2} = 2 + 2 + 3 + 2 = 9
  • {2, 3, 2, 2} = 2 + 3 + 2 + 2 = 9
  • {3, 2, 2, 2} = 3 + 2 + 2 + 2 = 9

Input: N = 2, X = 3, coins[] = {1, 2}
Output: 3
Explanation: There are 3 ways to make sum = 3

  • {1, 1, 1} = 1 + 1 + 1 = 3
  • {1, 2} = 1 + 2 = 3
  • {2, 1} = 2 + 1 = 3

Approach: To solve the problem, follow the below idea:

The problem can be solved using Dynamic Programming. We can maintain a dp[] array, such that dp[i] stores the number of distinct ways to produce sum = i. We can iterate i from 1 to X, and find the number of distinct ways to make sum = i. For any sum i, we assume that the last coin used was the jth coin where j will range from 0 to N - 1. For jth coin, the value will be coins[j], so the number of distinct ways to make sum = i, if the last coin used was the jth coin is equal to dp[i - coins[j]] + 1. Similarly, for every coin we can assume that this coin was the last coin used to make sum = i, and add the number of ways to the final answer. The formula for the ith sum will be: dp[i] = sum(dp[i - coins[j]]), for all j from 0 to N - 1.

Also, the above formula will be true only when coins[j] >= i.

Step-by-step algorithm:

  • Maintain a dp[] array such that dp[i] stores the number of distinct ways to make sum = i.
  • Initialize dp[0] = 1 as there is only 1 way to make sum = 0, that is to not take any coin.
  • Iterate i from 1 to X and calculate number of ways to make sum = i.
  • Iterate j over all possible coins assuming the jth coin to be last coin which was selected to make sum = i and add dp[i – coins[j]] to dp[i].
  • After all the iterations, return the final answer as dp[X].

Below is the implementation of the algorithm:


Output
8

Time Complexity: O(N * X), where N is the size of array coins[] and X is the sum we make using the coins.
Auxiliary Space: O(X)

Comment
Article Tags:
Article Tags: