MediumDynamic Programming · BFS

Coin Change

Given coin values coins (unlimited supply of each) and a target amount, return the fewest coins that add up to exactly amount, or −1 if it can't be made.

coins = [1,5,10], amount = 12 → 3coins = [2], amount = 3 → −1coins = [1], amount = 0 → 0

Try:
CALL
1 / 1

Code

The highlighted line runs next. The pill shows the live values in the running call.

Variables

The data structures the code is building

Totals 0 … amount

Number in each cell = fewest coins for that total

Time and space complexity

n = number of coin types, t = amount. The highlighted row is the solution being traced.

Keyboard: ← → step, Space play or pause. Up to 5 coin values from 1 to 30; drawings use amount ≤ 8 for plain recursion, 16 for top-down and 24 for bottom-up and BFS.