← Whiteboard questions

Fewest coins to make an amount

DSA, Medium

Which structure or algorithm, and what does it cost.

You have an unlimited supply of coins of some values, for example 1, 5 and 12. You get a list coins of the coin values and a whole number amount. Return the smallest number of coins that add up to exactly amount. If no combination makes the amount, return -1. If amount is 0, return 0.

Examples

Input coins = [1, 5, 12], amount = 15
Output 3
Why 5 + 5 + 5. Taking the biggest coin first (12 + 1 + 1 + 1) needs 4 coins.
Input coins = [4, 6], amount = 7
Output -1
Why Every sum of 4s and 6s is even, so 7 cannot be made.
Input coins = [3], amount = 0
Output 0
Why Edge case: the empty set of coins already makes 0.

Constraints

Your answer must contain

Fewest coins to make an amount · OpsKarma interview practice