What is Coin Change
Fewest coins that sum to amount, unlimited supply of each denomination. dp[x] is the fewest coins for sum x. Every coin c tries to improve dp[x] from dp[x-c] + 1.
Brute force approach
O(n^{amount/min}).Every coin is a branch from the remaining amount. The same remainder is expanded again and again. Memoization stores the fewest coins for each remainder.
Use at most 3 positive coins and an amount up to 7. 1 2 5 making 6 needs 2 coins (1+5).
Memoized approach
dp[x] = 1 + min(dp[x-c]). Each amount is solved once. Time O(n · amount).Each state is solved once. A dashed node is a cache hit: the call returns immediately and that branch stops.
1, 2, 5, amount 11. The table settles on 3 (5+5+1). Step through the DP table. The live code on the right is the DP recurrence — brute force is shown in Implementations below so you can see why it TLE.Interactive DP trace
Pseudocode & Complexity
| Operation | Time |
|---|---|
| Each (amount, coin) | O(1) |
| Fill table | O(amount · n) |
| Space | O(amount) |
Brute force explores the same subproblems many times and will TLE on the hidden tests. The DP codes below reuse each answer once.
Implementations