#322

Coin Change

Medium Unbounded knapsack (min coins)

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Return the fewest coins needed to make an amount using unlimited coins of given denominations, or -1 if impossible.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: fewest coins to make an amount.

Why this works: dp[a] = 1 + min over coins of dp[a - coin]. Greedy can fail; DP tries every last coin.

Example: coins [1, 2, 5], amount 11

dp[11] = dp[6] + 1 = (dp[1] + 1) + 1 = 3 (5 + 5 + 1)

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Using Integer.MAX_VALUE as infinity and then adding 1 — it overflows to negative.

Solve on LeetCode ↗
Complexity
  • Time: O(amount · coins).
  • Space: O(amount).
Topic: Dynamic Programming
🎬 Episodes 86–96: video coming soon