Created
April 29, 2018 18:21
-
-
Save mushifali/b6c0cab023072428c0defc5f4b3bb7df to your computer and use it in GitHub Desktop.
This is Coin Change Implementation in Java using Recursion and Dynamic Programming
This file contains 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
import java.util.Arrays; | |
import java.util.HashMap; | |
import java.util.Map; | |
public class CoinProblem { | |
public static void main(String[] args) { | |
System.out.println(countMakeChangeCombinations(new int[]{1, 2, 5}, 7)); | |
System.out.println(countMinimumChangeCoins(new int[]{1, 2, 5}, 7)); | |
} | |
public static int countMakeChangeCombinations(int[] coins, int money) { | |
return countMakeChangeCombinations(coins, money, 0, new HashMap<>()); | |
} | |
public static int countMakeChangeCombinations(int[] coins, int money, int index, Map<String, Integer> memo) { | |
if(money == 0) | |
return 1; | |
if(index >= coins.length) | |
return 0; | |
String key = money + "-" + index; | |
if(memo.containsKey(key)) | |
return memo.get(key); | |
int amountWithCoins = 0; | |
int ways = 0; | |
while(amountWithCoins <= money) { | |
int remaining = money - amountWithCoins; | |
ways += countMakeChangeCombinations(coins, remaining, index+1, memo); | |
amountWithCoins += coins[index]; | |
} | |
memo.put(key, ways); | |
return ways; | |
} | |
public static int countMinimumChangeCoins(int coins[], int money) { | |
Arrays.sort(coins); | |
int count = 0; | |
int remaining = money; | |
int index = coins.length - 1; | |
while(index >= 0) { | |
if(remaining >= coins[index]) { | |
remaining -= coins[index]; | |
count++; | |
} | |
else | |
index--; | |
} | |
if(remaining == 0) | |
return count; | |
else | |
return 0; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment