-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMinimum Coin Change (Top Down).cs
70 lines (51 loc) · 1.78 KB
/
Minimum Coin Change (Top Down).cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
using System;
using System.Collections.Generic;
namespace Algorithms
{
//Quick and Dirty Class that depicts the Top Down approach
//for finding minimum coins required for making change for a specific amount.
//Find more details at https://www.linkedin.com/pulse/dynamic-programming-part-2-amritpal-singh
public class Program
{
public static Dictionary<int, int> sumCoins = new Dictionary<int, int>();
//This variable is not needed for the algorithm. I took it to measure the time complexity
public static int TotalCounter = 0;
public static void Main(string[] args)
{
//Array of coin denominations
int[] coins = {1,5,6,9};
//Total amount we are trying to make
int balance = 11;
//Call the funtion
minCoinsTopDown(coins, balance);
Console.WriteLine("Min Coins required:" + minChange[balance] + "\nComplexity:" + TotalCounter);
}
public static void minCoinsTopDown(int[] coins, int balance)
{
//if we have reached 0 balance, return;
if(sum == 0) return 0;
//If the dictionary contains the minimum coins for the current Sum, return the number of coins
if(sumCoins.ContainsKey(sum))
{
return sumCoins[sum];
}
else
{
int numberOfCoins = 0;
int min = 999999;
for(int counter = 0 ; counter < coins.Length ; counter++)
{
if(sum >= coins[counter])
{
numberOfCoins = 1 + Math.Min(min, MinCoins(coins, sum - coins[counter]));
if(numberOfCoins < min)
{
min = numberOfCoins ;
}
}
}
sumCoins.Add(sum, min);
return min;
}
}
}