InferenceAI

Enter at least two characters to search.

Start free

Fewest Coins

mediumDynamic Programming25 min25 XP

Given coin denominations coins (unlimited supply) and an amount, return the fewest coins that add up to amount, or -1 if it is impossible.

dp[a]=1+min⁡c∈coins, c≤adp[a−c]\text{dp}[a] = 1 + \min_{c \in \text{coins},\, c \le a} \text{dp}[a - c]

Examples

EXAMPLE WALKTHROUGH5 + 5 + 1

A guided view of the published example, not a trace of your code.

INPUT[[1,2,5],11]
TASKfewest_coins()
EXPECTED OUTPUT3

Start with the input values shown in this example.

Example 1 of 3

Input: coins = [1,2,5], amount = 11

Output: 3

Explanation: 5 + 5 + 1

Input: coins = [2], amount = 3

Output: -1

Explanation: impossible

Input: coins = [1], amount = 0

Output: 0

Explanation: zero amount

Hint 1

Build the answer for every amount from 0 up to the target.

Topics

DSADynamic ProgrammingPython