KatInterview

Minimum Tokens to Reach a Score: Reusable vs. One-Time Use

Dynamic ProgrammingAuto-graded · 30 test cases
MediumAuto-gradedDynamic Programmingdynamic-programmingknapsackbottom-up-dp

Last 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 in tokens represents a denomination in unlimited supply — you may use that value as many times as you like.
  • reusable = False: each entry in tokens is 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 target is 0, the answer is always 0 — 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 3 twice counts as two tokens.
  • Return -1 when there is no exact way to reach target under the active rule.

Constraints

  • 1 <= len(tokens) <= 100
  • 1 <= tokens[i] <= 10^4
  • 0 <= 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…