Fewest Coins to Form Target Sum
Dynamic ProgrammingAuto-graded · 22 test casesLast updated
Tests dynamic programming with unbounded resources to compute the minimal coin count for a target value, handling impossible cases.
You have access to an unlimited supply of coins in various denominations and need to form a specific target sum.
Write a function that calculates the smallest number of coins required to reach exactly the target sum. When no valid combination exists, return -1. When the target is 0, return 0.
The denominations list may include repeated values and need not be in any particular order.
Function Signature
def fewest_coins(denominations: List[int], target: int) -> int:
pass
Input
denominations: A list of positive integers representing available coin valuestarget: A non-negative integer sum to achieve
Output
An integer: the minimum coin count needed, or -1 if the target cannot be formed
Constraints
1 <= len(denominations) <= 1001 <= denominations[i] <= 10^40 <= target <= 10^4
Examples
Example 1
Input: fewest_coins([1, 2, 5], 11)
Output: 3
Example 2
Input: fewest_coins([2], 3)
Output: -1
Example 3
Input: fewest_coins([1, 2, 5], 0)
Output: 0
Hints
Hint 1
Consider building up from zero rather than breaking down from the target
Hint 2
A greedy approach of always taking the largest coin won't always give the optimal result
Hint 3
Think about this as a graph where each sum is a node and adding a coin creates an edge to a new sum
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem requires finding the optimal combination of coins with unlimited supply, which rules out greedy strategies. A greedy method that always selects the largest coin fails for many denomination sets. For instance, with coins [1, 3, 4] targeting sum 6, greedy produces 4 + 1 + 1 (three coins) while the optimal solution is 3 + 3 (two coins).
Instead, we use dynamic programming. Define dp[s] as the minimum number of coins needed to form sum s. The recurrence relation is:
dp[0] = 0
dp[s] = min(dp[s - c] + 1) for all coins c where c <= s
To form sum s optimally, we must end with some coin c, leaving s - c to be formed optimally. This gives the problem its optimal substructure.
We initialize a table with target + 1 as a sentinel representing impossibility. Since each coin has value at least 1, any achievable sum uses at most target coins, making target + 1 safely distinguishable from any valid answer.
We iterate through each distinct denomination (deduplicating to avoid wasted computation). For each coin, we scan sums in ascending order from the coin's value up to the target. Processing in ascending order is crucial: when updating dp[s], the value dp[s - coin] may already reflect using that same coin, enabling unlimited reuse.
After processing all denominations, if dp[target] still holds the sentinel value, the target is unreachable and we return -1. Otherwise, we return dp[target].
Why It Works
The algorithm maintains this invariant: after processing the first k distinct denominations, dp[s] holds the minimum coins needed to form s using only those k denominations, or the sentinel if unreachable.
The base case trivially holds with dp[0] = 0 and all other entries as sentinels. When incorporating a new coin c, we scan upward through sums. The optimal solution for sum s either doesn't use c (already captured in dp[s]), or uses at least one c. In the latter case, removing one c leaves an optimal solution for s - c that may itself contain more copies of c. Since s - c < s, that entry was already updated during this pass, so dp[s - c] + 1 correctly captures all solutions using c.
The sentinel prevents contamination: adding 1 to a sentinel yields target + 2, which never wins against valid solutions or even against the original sentinel via the min operation.
Complexity
Time complexity: O(D · T) where D is the number of distinct denominations and T is the target value. With at most 100 distinct denominations and target at most 10⁴, this yields roughly 10⁶ operations.
Space complexity: O(T) for the DP array, plus O(D) for the deduplication set.
Solution
from typing import List
def fewest_coins(denominations: List[int], target: int) -> int:
# Track minimum coins needed for each sum; target + 1 serves as infinity
# since any achievable sum uses at most `target` coins (each coin >= 1)
min_coins_for_sum = [target + 1] * (target + 1)
min_coins_for_sum[0] = 0
# Remove duplicates to avoid redundant work
for coin_value in set(denominations):
# Process sums in ascending order to allow unlimited coin reuse
for current_sum in range(coin_value, target + 1):
min_coins_for_sum[current_sum] = min(
min_coins_for_sum[current_sum],
min_coins_for_sum[current_sum - coin_value] + 1
)
return min_coins_for_sum[target] if min_coins_for_sum[target] <= target else -1