Coin Change

Medium#3221d array

You get coin values, as many coins of each as you like, and an amount. Pay the amount exactly with as few coins as possible, or return -1 if it cannot be done. Our example: coins [3, 5, 6], amount 10 — 2 coins, 5 + 5.

input
coins: the values of the coins, as many of each as you like; amount: the sum to make.
returns
The fewest coins that add up to exactly amount; -1 if no coins do. For amount = 0 it is 0.
constraints
  • 1 ≤ coins.length ≤ 12
  • 1 ≤ coins[i] ≤ 2³¹ − 1
  • 0 ≤ amount ≤ 10⁴
our 12 tests keep to them
examples
Open a test in the tests panel: it shows the input and the expected answer.
/**
 * @param {number[]} coins
 * @param {number} amount
 * @return {number}
 */
function coinChange(coins, amount) {

}
Ctrl ↵
format
reset

saved in this browser

12 tests · limit 3 s

Stuck?

See the solution run step by step on our example, then why it works and its complexity.

Watch the walkthrough →

Next: more dynamic programming (dp) problems

Pattern “Dynamic programming (DP)” →

The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.