Compute number of ways to make amount of money with coins of the available denominations.

Below code snippet is easiest way to compute number of ways to make amount of money with coins of the available denominations.

Example: for amount=20 and denominations 20, 10, 5, 1, program should output 10 ways.

    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(MaxPossibleCombinations(4, new int[] { 1,2,3}));
            Console.WriteLine(MaxPossibleCombinations(20, new int[] { 20, 10, 5, 1 }));
            Console.ReadLine();
        }

        public static int MaxPossibleCombinations(int amount, int[] denominations)
        {
            int[] wayofDoingNAmount = new int[amount + 1];
            wayofDoingNAmount[0] = 1;
            foreach (int coin in denominations)
            {
                for (int higherAmount = coin; higherAmount < amount + 1; higherAmount++)
                {
                    int remainderAmount = higherAmount - coin;
                    wayofDoingNAmount[higherAmount] += wayofDoingNAmount[remainderAmount];
                }
            }
            return wayofDoingNAmount[amount];
        }
    }

This can also be achieved using the memoize technique. Memoization ensures that a function doesn’t run for the same inputs more than once by keeping a record of the results for given inputs (usually in a hash map).

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s