v9.1.1
Menu

Coin Change

mediumFREEDynamic ProgrammingNetflix DSA

Given coin denominations coins and a target amount, return the fewest coins needed to make up exactly amount. You may use each denomination any number of times. Return -1 if the amount cannot be made (and 0 when amount is 0).

Implement coin_change(coins, amount).

Example

Input
1,2,5
11
Output
3
Reasoning
  • coins lists the denominations {1,2,5}\{1, 2, 5\}, and each one can be used as many times as you like. amount is the target, 1111.
  • The output is a count of coins, not the coins themselves: the smallest kk such that kk denominations (repeats allowed) add up to exactly 1111.
  • Lower bound: even using only the biggest coin, 2×5=10<112 \times 5 = 10 < 11, so two coins can never reach 1111. At least 33 are needed.
  • Three coins do work: 5+5+1=115 + 5 + 1 = 11. Since 33 is both reachable and a lower bound, the answer is 3.
  • Notice that reaching for the largest coin first is not reliable in general: with denominations {1,3,4}\{1, 3, 4\} and target 66, starting with 44 forces 4+1+14 + 1 + 1 (three coins), while 3+33 + 3 needs only two.
  • If no combination hits the target exactly (denominations {2}\{2\}, target 33: every sum is even), the answer is −1-1; a target of 00 needs 00 coins.

Constraints

  • 1 <= len(coins) <= 12
  • 1 <= coins[i] <= 2^31 - 1
  • 0 <= amount <= 10^4

More from Netflix DSA

solution.py

Test results

Sign in to run your code against the test cases.