Last active
July 27, 2017 10:52
-
-
Save kriznaraj/1ca68ed344e585e32e8b31a37e6049fb to your computer and use it in GitHub Desktop.
The Coin Change Problem (Solution for https://www.hackerrank.com/challenges/coin-change)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using System; | |
| using System.Linq; | |
| using System.Collections; | |
| using System.Collections.Generic; | |
| namespace coinchange | |
| { | |
| struct DpEntry | |
| { | |
| public DpEntry(int n, int i) | |
| { | |
| this.n = n; | |
| this.i = i; | |
| } | |
| public int n; | |
| public int i; | |
| } | |
| class Program | |
| { | |
| private static Dictionary<DpEntry, Int64> dp; | |
| static void Main(string[] args) | |
| { | |
| var x = Console.ReadLine().Split(' ').Select(int.Parse).ToArray(); | |
| var coins = Console.ReadLine().Split(' ').Select(int.Parse).ToArray(); | |
| dp = new Dictionary<DpEntry,Int64>(); | |
| Console.WriteLine(changeDp(coins, x[0], 0)); | |
| Console.ReadKey(); | |
| } | |
| //Non dp solution | |
| static int change(int[] coins, int n, int i) | |
| { | |
| if(n == 0) | |
| { | |
| return 1; | |
| } | |
| return (n - coins[i] < 0 ? 0 : change(coins, n - coins[i], i)) + (i + 1 < coins.Length ? change(coins, n, i + 1) : 0); | |
| } | |
| //Dp solution using the memoization to store and reuse redundant calls made | |
| static Int64 changeDp(int[] coins, int n, int i) | |
| { | |
| if(n == 0) | |
| { | |
| return 1; | |
| } | |
| if(!dp.ContainsKey(new DpEntry(n,i))) | |
| { | |
| dp[new DpEntry(n,i)] = (n - coins[i] < 0 ? 0 : changeDp(coins, n - coins[i], i)) + (i + 1 < coins.Length ? changeDp(coins, n, i + 1) : 0); | |
| } | |
| return dp[new DpEntry(n,i)]; | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment