Minimum Tokens to Reach a Score: Reusable vs. One-Time Use
Dynamic ProgrammingAuto-graded · 30 test casesLast updated
Tests whether a candidate can implement both unbounded and 0/1 knapsack DP to find the smallest number of tokens that sum exactly to a target.
You are managing a collection of tokens, each with a point value. Given a list of token values tokens and a target score target, find the smallest number of tokens whose values sum to exactly target. Return -1 if no combination works.
The parameter reusable controls the supply rules:
reusable = True: each value intokensrepresents a denomination in unlimited supply — you may use that value as many times as you like.reusable = False: each entry intokensis a distinct physical token that may be spent at most once. Two entries with the same value are two separate tokens, each usable once.
Rules
- If
targetis0, the answer is always0— spending no tokens is valid under both rules. - The answer is a count of tokens spent, not a count of distinct values. Spending the value
3twice counts as two tokens. - Return
-1when there is no exact way to reachtargetunder the active rule.
Constraints
1 <= len(tokens) <= 1001 <= tokens[i] <= 10^40 <= target <= 10^4
Examples
Example 1
Input: fewest_coins([1, 3, 4], 6, True)
Output: 2
Example 2
Input: fewest_coins([1, 3, 4], 6, False)
Output: -1
Example 3
Input: fewest_coins([2, 5, 2, 2], 6, False)
Output: 3
Hints
Hint 1
Start by defining what dp[s] means: the fewest tokens that sum to exactly s. Set dp[0] = 0 and mark every other score as unreachable with a sentinel value larger than any possible valid answer — why is target + 1 a safe sentinel here?
Hint 2
For the reusable case, any denomination can contribute to dp[s] at any point in the computation. Build dp from s = 1 up to target, and for each s take the best result over all denominations c <= s. Because you go upward and any value may be reused, this is the unbounded knapsack recurrence.
Hint 3
For the one-time-use case, process tokens one at a time and iterate s from high to low (from target down to the token's value). The descending direction is the key: when you update dp[s] using dp[s - c], the value dp[s - c] has not been touched yet in this pass, so the current token can only be counted once. An ascending loop would allow the same token to be reused, collapsing this into the reusab…
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Both cases use a one-dimensional DP table. Define dp[s] as the fewest tokens that sum to exactly s. Initialize dp[0] = 0 (zero tokens needed to reach zero) and every other entry to a sentinel INF = target + 1. The sentinel is safe because every token value is at least 1, so any valid selection uses at most target tokens — any entry still equal to INF at the end was never reached.
Reusable supply (unbounded knapsack)
Build dp from s = 1 up to target. For each score s, try every denomination c that fits (c <= s) and take the minimum:
dp[s] = 1 + min(dp[s - c]) over all c <= s
Because we iterate upward and every denomination is always available, the same value can contribute at multiple steps — that is exactly what unlimited supply means. Deduplicating the token list before this loop avoids redundant work without changing any answer.
One-time-use (0/1 knapsack)
Process each physical token in turn. For token with value c, iterate s from high to low, updating:
dp[s] = min(dp[s], dp[s - c] + 1)
The descending direction is what enforces single use. When we compute dp[s], the cell dp[s - c] has not yet been touched in this pass, so it still reflects the state before this token was considered. That guarantees the token is counted at most once. Iterating upward instead would allow the same token to feed into itself repeatedly, which would silently turn this into the reusable problem.
Duplicate entries in tokens are kept as separate loop iterations — that is how three separate 2-tokens can together reach a sum of 6 even though no single denomination of 2 could be reused.
Why greedy fails
Taking the largest token that fits at each step is not optimal. With values [1, 3, 4] and target 6, greedy picks 4 + 1 + 1 (three tokens), while 3 + 3 uses only two.
Complexity
Let n = len(tokens) and A = target.
- Reusable: O(A · d) time where
d ≤ nis the number of distinct usable values; O(A) space. - One-time-use: O(n · A) time; O(A) space.
Both are at most roughly 10^6 operations given the stated constraints.
Edge cases
target = 0→ return0immediately; no tokens needed.- Every token exceeds
target→dpis never updated; return-1. - Duplicate values in reusable mode → safely deduplicated (redundant denominations change nothing).
- Duplicate values in one-time-use mode → must not deduplicate; each copy is a separate usable token.
Reference solution
from typing import List
def fewest_coins(tokens: List[int], target: int, reusable: bool) -> int:
if target == 0:
return 0
INF = target + 1 # any real answer uses at most `target` tokens
dp = [INF] * (target + 1)
dp[0] = 0
if reusable:
# Unbounded knapsack: deduplicate values and build scores upward.
vals = sorted(set(t for t in tokens if t <= target))
for s in range(1, target + 1):
best = INF
for c in vals:
if c > s:
break
v = dp[s - c]
if v < best:
best = v
dp[s] = best + 1 if best < INF else INF
else:
# 0/1 knapsack: one physical token per list entry; sweep scores downward.
hi = 0 # largest score reachable so far
for c in tokens:
if c > target:
continue
top = min(target, hi + c)
for s in range(top, c - 1, -1):
v = dp[s - c] + 1
if v < dp[s]:
dp[s] = v
hi = top
return dp[target] if dp[target] < INF else -1