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: 0
💡 Note: With coins 1,2,3 we can make all sums 1 to 7: 1, 2, 3, 4(1+3), 5(2+3), 6(1+2+3), 7(1+3+3 or others). No additions 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 AddedInputcoins = [1,3], target = 6Current Coverage✓ Can make: 1, 3, 4✗ Missing: 2, 5, 6SolutionAdd coin 2After Adding Coin 2:Can now make: 1, 2, 3, 4(1+3), 5(2+3), 6(1+2+3)Output: 1 (minimum coins needed)Greedy approach finds optimal solution efficiently
Understanding the Visualization
1
Input Analysis
Given coins and target, find what sums are missing
2
Gap Detection
Identify gaps in achievable sum coverage
3
Optimal Addition
Add minimum coins to fill all gaps
Key Takeaway
🎯 Key Insight: Sort coins and track maximum achievable sum - add coins only when gaps are found
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