Back to questions
You are given an integer array coins representing of different denominations and an integer representing a total amount of money.
Return the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1.
You may assume that you have an infinite number of each kind of coin.
Input: coins = [2, 4, 1, 4], target_amount = 5
Output: 2
Explanation:
There are several combinations to make up the amount , such as:
The combination that uses the fewest coins is the last one (using and ), which totals 2 coins.
Input: coins = [2], target_amount = 3
Output: -1
Explanation:
It is impossible to make up the amount using only the coin , since cannot be combined in any way to reach . Therefore, the output is .
This approach explores all possible ways to reach the by either:
Since we don’t know which combination of coins will yield the minimum count, we try all options recursively and pick the smallest valid result.
Here’s the code:
Think of each coin as a building block for constructing an amount. If you’re trying to make an amount using a coin of value , the remaining portion to be constructed is . If you already know the minimum number of coins needed to make the smaller amount (), you can just add 1 to include the current coin.
For example:
By repeating this process for all coins and all amounts up to the target amount, we can determine the minimum number of coins needed for each value.
We’ll use an array to keep track of the minimum number of coins needed to make each amount from to the target amount. Here’s the plan:
Create an array of size , where each index represents an amount. Set all values to infinity (), except which is (since it takes zero coins to make an amount of ).
For each coin in the list, check if it can contribute to constructing amounts starting from its value up to the target amount.
For each amount that the coin can contribute to, calculate the number of coins needed:
If the value at remains infinity, it means it’s impossible to make the target amount, so return .
Here is the code: