Recently I challenged my co-worker to write an algorithm to solve this problem:
Find the least number of coins required that can make any change from
Solution with greedy approach in java is as below :
public class CoinChange {
public static void main(String args[]) {
int denominations[] = {1, 5, 10, 25};
System.out.println("Total required coins are " + greeadApproach(53, denominations));
}
public static int greeadApproach(int amount, int denominations[]) {
int cnt[] = new int[denominations.length];
for (int i = denominations.length-1; amount > 0 && i >= 0; i--) {
cnt[i] = (amount/denominations[i]);
amount -= cnt[i] * denominations[i];
}
int noOfCoins = 0;
for (int cntVal : cnt) {
noOfCoins+= cntVal;
}
return noOfCoins;
}
}
But this works for single amount. If you want to run it for range, than we have to call it for each amount of range.