Implement the coinChangeMinimumCoins method that returns the minimum number of coins needed to make the amount.

The input contains coin denominations coins, their count size, and a target amount.

Your task is to return the minimum number of coins needed to make exactly that amount. You may use each coin denomination multiple times.

If the amount cannot be formed using the given coins, return -1. For example, with coins [1,2,5] and amount 11, the minimum number of coins is 3 using 5 + 5 + 1.

Example 1

Input
coins (int[]) = [1,2,5]
size (int) = 3
amount (int) = 11
Returns (int) 3

Example 2

Input
coins (int[]) = [2]
size (int) = 1
amount (int) = 3
Returns (int) -1

Example 3

Input
coins (int[]) = [1]
size (int) = 1
amount (int) = 0
Returns (int) 0

Use dynamic programming where dp[x] stores the minimum coins required to form amount x.

Start with dp[0] = 0 because zero coins are required to form amount zero. For every amount, try every coin. If the coin can be used, update the answer from the smaller amount amount - coin.

After filling the table, if the target amount still has a large impossible value, return -1.

Pseudocode:

function coinChangeMinimumCoins(coins, size, amount):
    dp = array of amount + 1 filled with infinity
    dp[0] = 0
    for value from 1 to amount:
        for each coin in coins:
            if coin <= value:
                dp[value] = min(dp[value], dp[value - coin] + 1)
    if dp[amount] is infinity:
        return -1
    return dp[amount]
Ready to test your solutionRun Code checks your solution against the test cases.Shift + Enter to run

Notifications

Updates are enabled for this browser.

Receive new tutorials, articles and learning resources. You can turn updates off anytime.

Test browser code

Use this code in admin to send a test notification to this browser.