Friday, October 15, 2010

Algorithm to find the least number of coins

This is a simplest puzzle asked in interviews. You are given coins of denominations 5 Rs, 2 Rs, 1 Re, 50 Paisa, 25 Paisa and 10 Paisa. For any given currency value (assume > 10 Rs), determine the change to be given in coins. While doing this ensure that the number of coins are minimum.

Solution:
public class ChangeGenerator {
/**
* @param args
*/
public static void main(String[] args) {
int[] denos = {500, 200, 100, 50, 25, 10};
int value = 3785;
getChange( denos, value);
}
private static void getChange(int[] denos, int value) {
int toCalculate = value;
for( int deno: denos ) {
if( toCalculate == 0 )
break;
if( toCalculate >= deno ) {
int coins = toCalculate/deno;
toCalculate = toCalculate - (coins*deno);
if( deno > 50 ) {
System.out.println(coins + " of " +(deno/100) + " Rs");
} else {
System.out.println(coins + " of " + deno + " Paisa");
}
} else {
continue;
}
}
}
}
view raw gistfile1.java hosted with ❤ by GitHub


UA-36403895-1