Skip to content

Instantly share code, notes, and snippets.

@madhur
Created July 27, 2019 14:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save madhur/208a2a69c1a449321eaeb7e22e9d27fe to your computer and use it in GitHub Desktop.
Save madhur/208a2a69c1a449321eaeb7e22e9d27fe to your computer and use it in GitHub Desktop.
Make change
// java.util.* and java.util.streams.* have been imported for this problem.
// You don't need any other imports.
public static int makeChange(int[] coins, int amount) {
int counter = 0;
int currentCoinIndex = 0;
Integer[] answer = new Integer[1];
answer[0] = 0;
for(int i=100;i>0;--i){
makeChangeSum(coins, currentCoinIndex, amount,i, answer, amount);
}
return answer[0];
}
private static int makeChangeSum(int[] coins, int currentCoinIndex, int remainingAmount, int multiplier, Integer[] answer, int amount) {
if(currentCoinIndex == coins.length || multiplier > remainingAmount) {
return 0;
}
System.out.println("Index: " + coins[currentCoinIndex] + " remainingAmount: " + remainingAmount + " multiplier: " + multiplier);
if(coins[currentCoinIndex] * multiplier == remainingAmount) {
System.out.println("Answer: " + coins[currentCoinIndex] + " remainingAmount: " + remainingAmount + " multiplier: " + multiplier);
answer[0]++;
makeChangeSum(coins, currentCoinIndex + 1, amount, multiplier, answer, amount);
}
else if (coins[currentCoinIndex] * multiplier > remainingAmount) {
System.out.println("Decreasing coin index to : " + (currentCoinIndex+1));
makeChangeSum(coins, currentCoinIndex + 1, remainingAmount, multiplier, answer, amount);
}
else if (coins[currentCoinIndex] * multiplier < remainingAmount) {
remainingAmount = remainingAmount - coins[currentCoinIndex]*multiplier;
System.out.println("Decreasing multiplier to : " + (multiplier-1) + " remainingAmount: " + remainingAmount);
makeChangeSum(coins, currentCoinIndex+1, remainingAmount, multiplier-1, answer, amount);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment