How to implement coin change problem using topDown approach using C#?

CsharpServer Side ProgrammingProgramming

CoinChangeTopDownApproach takes 4 parameters, n is the amount, coins array contains the coins from which the amount needs to be calculated, t is the total number of coins, dp array will store all the pre calculated values. If amount is 0 then return 0. If the value is already calculated then return from the dp array. if the value is not calculated then call the CoinChangeTopDownApproach recursively.

Time complexity − O(N)

Space complexity − O(N)

Example

public class DynamicProgramming{
   public int CoinChangeTopDownApproach(int n,int[] coins,int t,int[] dp){
      if (n == 0){
         return 0;
      }
      if (dp[n] != 0){
         return dp[n];
      }
      int ans = int.MaxValue;
      for (int i = 0; i < t; i++){
         if (n - coins[i] >= 0){
            int subprob = CoinChangeTopDownApproach(n - coins[i], coins, t, dp);
            ans = Math.Min(ans, subprob + 1);
      }
   }
   dp[n] = ans;
   return dp[n];
   }
}

static void Main(string[] args){
   DynamicProgramming dp = new DynamicProgramming();
   int N = 15;
   int[] coins = { 1, 7, 10 };
   int[] dp1 = new int[100];
   int t = coins.Count();
   int res = dp.CoinChangeTopDownApproach(15, coins, t, dp1);
   Console.WriteLine(res);
}

Output

3
raja
Published on 17-Aug-2021 08:23:55
Advertisements