VOOZH about

URL: https://www.geeksforgeeks.org/dsa/cses-solutions-missing-coin-sum/

⇱ CSES Solutions - Missing Coin Sum - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

CSES Solutions - Missing Coin Sum

Last Updated : 23 Jul, 2025

You are given an array of positive integers coins[] of size n, representing n coins of different denominations. The task is to find the smallest sum that can not be created using a subset of the coins[].

Note: Each coin can only be used once.

Examples:

Input: coins[] = [2, 9, 1, 2, 7]
Output: 6
Explanation:

  • Sum = 1, we can take the coin with value 1.
  • Sum = 2, we can take the coin with value 2.
  • Sum = 3, we can take coins with value 1 and 2.
  • Sum = 4, we can take coins with value 2 and 2.
  • Sum = 5, we can take coins with value 1, 2 and 2.
  • Sum = 6, no possible subset of coins can sum up to 6.

Input: coins[] = [1, 2, 3]
Output: 7
Explanation:

  • Sum = 1, we can take the coin with value 1.
  • Sum = 2, we can take the coin with value 2.
  • Sum = 3, we can take coins with value 3.
  • Sum = 4, we can take coins with value 1 and 3.
  • Sum = 5, we can take coins with value 2 and 3.
  • Sum = 6, we can take coins with value 1, 2 and 3.
  • Sum = 7, no possible subset of coins can sum up to 7.

Approach:

The idea is to use Greedy approach to solve the problem. We start from the coins of smallest value and build up the sum of coins we can form. Let's say we have some coins whose total value is val, so the maximum value of the next coin can be val + 1. If the next coin has a value greater than val + 1 then (val + 1) is the smallest sum which we cannot create using any subset of coins. Otherwise, if the value of the next coin is less than (val + 1) we can add it to the total value to get the new total sum val.

Step-by-step algorithm:

  • Sort the array of coins in increasing order of values.
  • Maintain a variable val, initialized with value 1, which stores the maximum value of the next coin.
  • Iterate from 0 to n - 1, and check if arr[i] > val or not.
  • If arr[i] > val, return val as the answer.
  • Else if arr[i] <= val, update val = val + arr[i].
  • After all the iterations if we haven't returned yet, return (val) as the answer.

Below is given the implementation:


Output
6

Time Complexity: O(n * log(n)), where n is the number of coins. We are sorting the array and then traversing it, thus the overall complexity will be O(n* log(n) + n)) ~= O(n * log(n))
Auxiliary Space: O(1), as we are using no extra space.

Comment
Article Tags:
Article Tags: