Skip to content
mlmentorship

Remove the final coin and reuse the best smaller total

Solve amount-indexed minimum counts, justify the unreachable sentinel, then recover an optimal witness or minimize unequal costs.

Published · 33 min read ·Core ·Mixed

ML breadth · active recall

Practice before you read

8 minutes. Explain the mechanism, why it works, when it fails, and one alternative.

ML breadth · closed-book attempt

Remove the final coin and reuse the best smaller total

Explain the mechanism, why it works, when it fails, and one alternative.

Problem

Input. An integer list coins of denominations and a nonnegative integer amount. Output. Return the smallest number of coins totaling exactly amount, or -1 if that amount is impossible. Rules. Each positive denomination may be used any number of times. Duplicate denominations do not change the answer; the reference ignores nonpositive denominations. Amount zero requires zero coins. Leave coins unchanged. Example. For coins = [2, 3] and amount = 7, return 3 using 2 + 2 + 3. For coins = [2] and amount = 3, return -1.

08:00recommended time

Closing or reloading clears the scratchpad. Only score, weak rubric dimensions, attempt count, and retry date can be stored locally.

30-second answer map

For each amount, minimize one plus every already-solved predecessor amount.

Problem trace

An unreachable predecessor supplies no valid coin-count candidate

Worked example: an unreachable predecessor supplies no valid solutionFor coins (2,3) and amount 3, coin 2 points to unreachable amount 1. Coin 3 points to base amount 0 and supplies count 1.A candidate needs a reachablesmaller-amount predecessorUse coin 2; subtract it from amount 331Sentinel means unreachable: rejectthis routeUse coin 3; subtract it from amount 330Reachable base: one coin completesthe amountThe valid amount-zero route suppliesthe one-coin answer.
Read it this way: For coins (2,3) and amount 3, coin 2 points to unreachable amount 1. Coin 3 points to base amount 0 and supplies count 1. Does an arithmetic candidate through unreachable amount one become a valid solution merely by adding one coin?
Full interview answer 33 min read

Find the fewest available coins needed to make an exact amount, with unlimited reuse of each denomination.

Problem

Input. An integer list coins of denominations and a nonnegative integer amount.

Output. Return the smallest number of coins totaling exactly amount, or -1 if that amount is impossible.

Rules. Each positive denomination may be used any number of times. Duplicate denominations do not change the answer; the reference ignores nonpositive denominations. Amount zero requires zero coins. Leave coins unchanged.

Example. For coins = [2, 3] and amount = 7, return 3 using 2 + 2 + 3. For coins = [2] and amount = 3, return -1.

Picture

Index a row by total amount, not by coin identity. Base fewest[0]=0 needs no coins. For a possible final coin, inspect fewest[total-coin] and add one. Every predecessor is smaller, so increasing totals solve dependencies first.

Initialize other entries to amount+1. Every feasible count is at most amount because each accepted coin contributes at least one. The sentinel therefore exceeds every feasible answer.

With coins 2,3, total 1 remains unreachable and totals 2,3 each need one coin. Total 6 initially needs three via coin 2, then improves to two via coin 3. Total 7 needs three, for example 2+2+3. The arrows point from the current total to the smaller dependency, including solved-but-unreachable predecessors.

Problem trace

An unreachable predecessor supplies no valid coin-count candidate

Input and goalFind the fewest coins needed to make an amount.
Initialize the DP rowfewest[0]=0 and amounts 1 through 7 use sentinel 8, meaning unreachable.
t=00081828384858687
examplecoins = [2, 3], amount = 7; unreachable = 8indexMeaningt = current total; p = total - coin; arrow points to pfewest[0,8,8,8,8,8,8,8]
t
0
example
coins = [2, 3], amount = 7; unreachable = 8
index meaning
t = current total; p = total - coin; arrow points to p

Recognize it
The target can be composed repeatedly from reusable coin values and asks for a minimum count, so each total depends on smaller totals.
Keep true
When processing total t, every fewest[x] for x<t is final; after trying each valid coin, fewest[t] is the minimum candidate examined so far.
Reuse it
Define the answer for one total from already-solved smaller totals and aggregate with min; this transfers to minimum steps, perfect squares, and shortest composition problems.
fewest[0]=0 and amounts 1 through 7 use sentinel 8, meaning unreachable. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why does 1 plus the stored sentinel not make an unreachable amount reachable?
Reference drawing

Problem trace

An unreachable predecessor supplies no valid coin-count candidate

Worked example: an unreachable predecessor supplies no valid solutionFor coins (2,3) and amount 3, coin 2 points to unreachable amount 1. Coin 3 points to base amount 0 and supplies count 1.A candidate needs a reachablesmaller-amount predecessorUse coin 2; subtract it from amount 331Sentinel means unreachable: rejectthis routeUse coin 3; subtract it from amount 330Reachable base: one coin completesthe amountThe valid amount-zero route suppliesthe one-coin answer.
Execution trace
Input and goalFind the fewest coins needed to make an amount.
Initialize the DP rowfewest[0]=0 and amounts 1 through 7 use sentinel 8, meaning unreachable.
t=00081828384858687
examplecoins = [2, 3], amount = 7; unreachable = 8indexMeaningt = current total; p = total - coin; arrow points to pfewest[0,8,8,8,8,8,8,8]
t
0
example
coins = [2, 3], amount = 7; unreachable = 8
index meaning
t = current total; p = total - coin; arrow points to p

Recognize it
The target can be composed repeatedly from reusable coin values and asks for a minimum count, so each total depends on smaller totals.
Keep true
When processing total t, every fewest[x] for x<t is final; after trying each valid coin, fewest[t] is the minimum candidate examined so far.
Reuse it
Define the answer for one total from already-solved smaller totals and aggregate with min; this transfers to minimum steps, perfect squares, and shortest composition problems.
fewest[0]=0 and amounts 1 through 7 use sentinel 8, meaning unreachable. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why does 1 plus the stored sentinel not make an unreachable amount reachable?
Read it this way: For coins (2,3) and amount 3, coin 2 points to unreachable amount 1. Coin 3 points to base amount 0 and supplies count 1. Does an arithmetic candidate through unreachable amount one become a valid solution merely by adding one coin?

Code

def coin_change(coins: list[int], amount: int) -> int:
   unreachable = amount + 1
   fewest = [0] + [unreachable] * amount

   for total in range(1, amount + 1):
      for coin in coins:
         if 0 < coin <= total:
            fewest[total] = min(fewest[total], 1 + fewest[total - coin])

   return fewest[amount] if fewest[amount] != unreachable else -1

Amount zero returns zero even without denominations. The input list remains unchanged. For amount and entries, time is and storage is . This is pseudo-polynomial in the numeric amount, not polynomial in its encoded bit length.

Failure Check

For [1,3,4] and amount 6, greedy 4+1+1 loses to 3+3. Initializing unreachable totals to zero would invent solutions to impossible predecessors.

Change to an Optimal Coin Witness

New task: Return actual coin values, or None if no construction exists.

Picture and change: Save the final coin on strict improvement, then repeatedly subtract saved coins to reconstruct the solution.

def minimum_coin_witness(coins, amount):
   unreachable = amount + 1
   fewest = [0] + [unreachable] * amount
   parent = [None] * (amount + 1)
   for total in range(1, amount + 1):
      for coin in coins:
         if 0 < coin <= total and fewest[total - coin] + 1 < fewest[total]:
            fewest[total] = fewest[total - coin] + 1
            parent[total] = coin
   if fewest[amount] == unreachable:
      return None
   result = []
   while amount:
      coin = parent[amount]
      result.append(coin)
      amount -= coin
   return result

Check: [1,3,4] and 6 return [3,3]; [2] and 3 return None. Amount zero returns []. Witness values sum to the target and witness length equals the optimal count. Equal-cost ties retain the first improving coin encountered; no lexical ordering is promised. Parent storage is linear in the target, with additional output storage for selected coins.

Use when: A count needs a concrete construction.

Change to Unequal Coin Costs

New task: Each positive denomination has a finite nonnegative int or float cost instead of unit cost.

Picture and change: Replace the unit increment with that cost; positive value progress still makes dependencies acyclic.

def minimum_coin_cost(coins_with_cost, amount):
   costs = [0] + [float("inf")] * amount
   for total in range(1, amount + 1):
      for value, cost in coins_with_cost:
         if 0 < value <= total and costs[total - value] != float("inf"):
            costs[total] = min(costs[total], costs[total - value] + cost)
   return None if costs[amount] == float("inf") else costs[amount]

Check: [(2,5),(3,1)] and amount 6 return cost 2, from two value-3 coins. The amount-based sentinel cannot bound arbitrary costs, so this variant uses infinity. Skipping unreachable predecessors keeps integer-cost arithmetic exact even beyond float range. Float costs remain approximate and require finite accumulated totals; infeasible targets return None.

Use when: Composition choices have unequal additive costs.

Transfer Check

Why can one best number replace all predecessor constructions?

Answer

Future feasibility depends only on the remaining amount, and adding the same final cost preserves preference for cheaper predecessors. Counting constructions would instead retain multiplicity.