Advertisement
martixy

Coin Counting Problem

Apr 13th, 2012
141
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.67 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Diagnostics;
  6.  
  7. namespace Z5_BuyGraphs
  8. {
  9.     class Program
  10.     {
  11.         // Dynamic programming, bottoms-up approach
  12.         // Ref: [http://www.ccs.neu.edu/home/jaa/CSG713.04F/Information/Handouts/dyn_prog.pdf]
  13.  
  14.         public static int[] denoms = { 1, 8, 9, 27, 28, 31, 36 };
  15.         public static int[] BigC;
  16.         public static int[] BigS;
  17.  
  18.         static void Main(string[] args)
  19.         {
  20.             int money = 46;
  21.             Console.WriteLine(CoinCounting(money));
  22.             while (money > 0)
  23.             {
  24.                 Console.Write(denoms[BigS[money]] + ", ");
  25.                 money -= denoms[BigS[money]];
  26.             }
  27.         }
  28.  
  29.         // O(NlogN + NK) //Sort + 2 loops
  30.         private static int CoinCounting(int changeThis)
  31.         {
  32.             int coinsNeededMin = 0;
  33.             int firstCoin = 0;
  34.             BigC = new int[changeThis + 1];
  35.             BigS = new int[changeThis + 1];
  36.  
  37.             Array.Sort(denoms);
  38.  
  39.             for (int i = 1; i <= changeThis; i++)
  40.             {
  41.                 coinsNeededMin = int.MaxValue;
  42.                 for (int j = 0; j < denoms.Length && denoms[j] <= i; j++)
  43.                 {
  44.                     int result = 1 + BigC[i - denoms[j]];
  45.                     if (result < coinsNeededMin)
  46.                     {
  47.                         coinsNeededMin = result;
  48.                         firstCoin = j;
  49.                     }
  50.                 }
  51.                 BigC[i] = coinsNeededMin;
  52.                 BigS[i] = firstCoin;
  53.             }
  54.             return coinsNeededMin;
  55.         }
  56.     }
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement