Problem Description
Given an array of coin values and a target value, determine 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] becomes obtainable as the sum of a subsequence of the coins.
Key Insights
- This problem is similar to the "Patching Array" problem.
- Sort the coins to process them in increasing order.
- Maintain a running sum (current reachable range) that indicates you can form every value in [1, current_sum].
- If the next coin is greater than current_sum + 1, then there is a gap that must be filled by adding a coin with value current_sum + 1.
- Continue this greedy strategy until the reachable range covers the target.
Space and Time Complexity
Time Complexity: O(n log n) due to sorting, where n is the number of coins. The subsequent processing is O(n). Space Complexity: O(1) additional space if sorting is done in place (ignoring the space for input).
Solution
The solution uses a greedy algorithm. First, sort the coins array. Then, using a pointer (or index) for the coins and a variable (current_sum) representing the maximum contiguous value that can be obtained (i.e., you can obtain every value in [1, current_sum]), iterate until current_sum is at least target. If the coin at the pointer is less than or equal to current_sum + 1, it extends the range; otherwise, add a coin of value current_sum + 1 to patch the gap. Increment the count for each coin added. This approach ensures that the minimum number of coins are added while extending the reachable range optimally.