How to implement coin change problem using bottom-up approach using C#?

CsharpServer Side ProgrammingProgramming

CoinChangeBottomUpApproach takes 3 parameters as input n is the amount, coins array contains the total number of coins, t contains total number of coins. Declare a dynamic array which stores the previously calculated values. loop through the array and calculate the minimum coins required to calculate the amount. If the calculation is already done the take the value from the dynamic array.

Time complexity − O(N)

Space complexity − O(N)

Example

public class DynamicProgramming{
   public int CoinChangeBottomUpApproach(int n,int[] coins,int t){
      int[] dp = new int[100];
      for (int i = 1; i < n; i++){
         dp[i] = int.MaxValue;
         for (int j = 0; j < t; j++){
            if (i - coins[j] >= 0){
               int subProb = dp[i - coins[j]];
               dp[i] = Math.Min(dp[i], subProb + 1);
            }
         }
      }
      return dp[n]+1;
   }
}

static void Main(string[] args){
   DynamicProgramming dp = new DynamicProgramming();
   int[] coins = { 1, 7, 10 };
   int ss = dp.CoinChangeBottomUpApproach(15, coins, coins.Count());
   Console.WriteLine(ss);
}

Output

3
raja
Published on 17-Aug-2021 08:28:11
Advertisements