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
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
public class LeastNumofCoins
{
public int getNumofCoins(int amount)
{
int denominations[]={50,25,10,5,2,1};
int numOfCoins=0;
int index=0;
while(amount>0)
{
int coin=denominations[index];
if(coin==amount)
{
numOfCoins++;
break;
}
if(coin<=amount)
{
amount=amount-coin;
numOfCoins++;
}
else
{
index++;
}
}
return numOfCoins;
}
public static void main(String[] args) throws IOException
{
Scanner scanner= new Scanner(new InputStreamReader(System.in));
System.out.println("Enter the Amount:");
int amoount=scanner.nextInt();
System.out.println("Number of minimum coins required to make "+ amoount +" is "+new LeastNumofCoins().getNumofCoins(amoount));
scanner.close();
}
}