Practice
JavaScriptData StructuresReactConcepts
Sign in
← Back to problems

Coin Change

Dynamic Programmingmedium

Given `coins` (an array of distinct denominations) and a target `amount`, implement `coinChange(coins, amount)` returning the fewest coins that sum to `amount`, or `-1` if it cannot be made. You may use each denomination any number of times. (Asked at Amazon, Microsoft, and Google.)

Examples

Input: coins = [1, 2, 5], amount = 11
Output: 3
5 + 5 + 1 = 11.
Input: coins = [2], amount = 3
Output: -1
No combination of 2s makes 3.

Sample tests

Input: coinChange([1,2,5], 11)
Output: 3
Input: coinChange([2], 3)
Output: -1

+ 2 hidden tests run on Submit.

Hints

Common pitfalls
  • A greedy 'largest coin first' strategy is wrong for arbitrary denominations (e.g. coins [1,3,4], amount 6).
  • Forgetting the unreachable case — leave it as Infinity and convert to -1 at the end.

Learning resources

  • Wikipedia: Dynamic programming
Approach & explanation (try first)

Bottom-up DP builds the answer for every amount from 0 up to the target. Each amount takes one more coin than the best reachable smaller amount. Unreachable amounts stay Infinity and map to -1. O(amount × coins) time.

Loading...
⌘/Ctrl + Enter

Run your code to see results.