◀ THE GRIND — 1-D DYNAMIC PROGRAMMING

Coin Change

MEDIUM✓ CHIP-TIMEDLC #322 — FULL STATEMENT ↗

The drill: A set of coin denominations and a target amount — find the fewest coins that sum to exactly that amount, with unlimited coins of each kind, or report it's impossible.

THE BRIEFING — THE FULL DRILL, IN MY OWN WORDS

A set of coin denominations arrives alongside a target amount, and an unlimited supply of each denomination is available to use.

The task is to reach the target amount exactly, using as few coins as possible from that unlimited supply, mixing denominations freely.

If no combination of the given coins can add up to the target exactly, that has to be signaled distinctly rather than returned as some default count.

EX 01
coins = [1, 2, 5] · amount = 11
3
CLASSIC MIXED DENOMINATIONS
EX 02
coins = [2] · amount = 3
-1
ODD TARGET, ONLY AN EVEN COIN
EX 03
coins = [1] · amount = 0
0
TARGET ALREADY ZERO
THE HINTS — TAKE ONLY WHAT YOU NEED
HINT 1 THE NUDGE

Trying every combination of coins to hit the amount branches at every denomination, at every remaining amount — what does the fewest-coins answer for amount a actually need from smaller amounts?

HINT 2 THE STRUCTURE

The fewest coins to make amount a is one plus the fewest coins to make a minus some coin's value, minimized over every coin — and every amount smaller than a can be solved first.

HINT 3 ONE STEP FROM THE ANSWER

Build a table from 0 up to the target: dp[a] = 1 + the smallest dp[a - c] over every coin c ≤ a, with dp[0] = 0. Any amount that stays unreachable answers -1.

COACH'S BOARD — THE PATTERN, STEP BY STEP
COINS FROM ZERO UPPATTERN · BOTTOM-UP AMOUNT DPcoins = [1, 3, 4] · amount = 6
0
STEP 1

dp[0] = 0 — zero coins needed for zero amount, the base case.

STEP 1 / 8 · ← → WORK TOO
THE SPLITS — TWO PACES, TWO LANGUAGES
grind/coin-change.pyRACE PACE
LANG ▸
PACE ▸
class Solution:
    def coinChange(self, coins: List[int], amount: int) -> int:
        dp = [0] + [math.inf] * amount
        for a in range(1, amount + 1):
            for c in coins:
                if c <= a:
                    dp[a] = min(dp[a], dp[a - c] + 1)
        return dp[amount] if dp[amount] != math.inf else -1
TIME O(AMOUNT·K)SPACE O(AMOUNT)PYTHON · RACE PACE · 8 LN

✓ CHIP-TIMED — ALL 4 SOLUTIONS RAN GREEN AGAINST SELF-AUTHORED CASES IN CI · JDK 21 · CPYTHON 3.12 · NOTHING PUBLISHES RED