Implementing the Solution
Now that we understand the optimized dynamic programming solution for the coin change problem, let's implement it in code.
Here's the C# code for the dynamic programming solution:
1{{code}}
In this implementation, we define a function CoinChange
that takes an array of coin denominations coins
and the desired change amount amount
as parameters.
We create an array dp
of size amount + 1
and initialize all its values to amount + 1
, except for dp[0]
which is set to 0
since we don't need any coins to make zero change.
We then iterate through the coins
array and for each coin coin
, we iterate from coin
to amount
. For each value i
, we update dp[i]
to be the minimum between its current value and dp[i - coin] + 1
. This represents the minimum number of coins needed to make the amount i
using the current coin and any previously calculated solutions.
Finally, we return dp[amount]
, which will be the minimum number of coins needed to make the given amount of change. If dp[amount]
is greater than amount
, it means that it was not possible to make the amount using the given coins, so we return -1
.
Now, let's run the code and see the output:
1Minimum number of coins needed: 3
xxxxxxxxxx
}
using System;
public class CoinChangeSolution
{
public static int CoinChange(int[] coins, int amount)
{
int[] dp = new int[amount + 1];
Array.Fill(dp, amount + 1);
dp[0] = 0;
for (int i = 1; i <= amount; i++)
{
for (int j = 0; j < coins.length; j++)
{
if (coins[j] <= i)
{
dp[i] = Math.Min(dp[i], dp[i - coins[j]] + 1);
}
}
}
return dp[amount] > amount ? -1 : dp[amount];
}
public static void Main(string[] args)
{
int[] coins = {2, 3, 5};
int amount = 11;
int minCoins = CoinChange(coins, amount);