Minimum Number of Coins to be Added - Problem

You are given a 0-indexed integer array coins, representing the values of the coins available, and an integer target.

An integer x is obtainable if there exists a subsequence of coins that sums to x.

Return the minimum number of coins of any value that need to be added to the array so that every integer in the range [1, target] is obtainable.

A subsequence of an array is a new non-empty array that is formed from the original array by deleting some (possibly none) of the elements without disturbing the relative positions of the remaining elements.

Input & Output

Example 1 — Basic Case
$ Input: coins = [1,3], target = 6
Output: 1
💡 Note: We can make sums 1, 3, 4 initially. Missing: 2, 5, 6. Add coin 2 to make all sums 1-6 possible: 1, 2, 3, 4(1+3), 5(2+3), 6(1+2+3).
Example 2 — Already Complete
$ Input: coins = [1,2,3], target = 7
Output: 1
💡 Note: With coins 1,2,3 we can make sums 1,2,3,4(1+3),5(2+3),6(1+2+3). To make 7, we need to add one more coin of value 4, giving us 7(3+4). So 1 addition is needed.
Example 3 — Large Gap
$ Input: coins = [1,5,10], target = 20
Output: 2
💡 Note: Can make 1, 5, 6, 10, 11, 15, 16. Missing many sums. Need to add coins 2 and 4 to fill gaps efficiently.

Constraints

  • 1 ≤ coins.length ≤ 105
  • 1 ≤ coins[i] ≤ 104
  • 1 ≤ target ≤ 104

Visualization

Tap to expand
Minimum Number of Coins to be Added INPUT coins array: 1 index 0 3 index 1 target: 6 Need to cover [1, 6]: 1 2 3 4 5 6 coins = [1, 3] target = 6 ALGORITHM STEPS 1 Sort coins [1, 3] already sorted 2 Initialize reach = 0 Track max obtainable sum 3 Process coin 1 1 <= reach+1, reach = 1 4 Gap detected! 3 > reach+1 (2), add 2 Execution Trace: reach=0 --> coin 1 --> reach=1 GAP! Add coin 2, reach=3 reach=3 --> coin 3 --> reach=6 reach >= target, DONE! Coins added: 1 (value: 2) FINAL RESULT 1 Minimum coins to add Modified array: 1 2 ADDED 3 All values [1-6] obtainable: 1 = 1 OK 2 = 2 OK 3 = 3 OK 4 = 1+3 OK 5 = 2+3 OK 6 = 1+2+3 OK Output: 1 Key Insight: The greedy approach maintains a "reach" value representing the maximum sum obtainable. If next coin > reach + 1, there's a gap! We add a coin equal to reach + 1 to fill it. This doubles our reach each time, giving O(n + log(target)) time complexity. TutorialsPoint - Minimum Number of Coins to be Added | Greedy - Sort and Fill Gaps
Asked in
Google 12 Amazon 8 Microsoft 6
28.4K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen