import java.util.Scanner; public class Coins { final static int MAX = Integer.MAX_VALUE; // Some insanely large value static int MakeChangeFor(int Amount, int[] v) { int[] sol, mySol; int myFinalSol; int C; // # different coins int k; C = v.length; // # different coin values sol = new int[v.length]; // Used to store sol for smaller problems mySol = new int[v.length]; // mySol[i] = my solution value using sol[i] /* --------------------------- Base cases --------------------------- */ if ( Amount == 0 ) { return(0); } /* -------------------------------------------------------- Initialize mySol[ ] to some illegal value -------------------------------------------------------- */ for ( k = 0; k < C; k++ ) mySol[k] = MAX; // Initialize mySol[] /* -------------------------------------------------------- Try every coin denomination -------------------------------------------------------- */ for ( k = 0; k < C; k++ ) { // Coin Value = v[k]; /* ------------------------------------------------- Check if we can use the k-th denomination If Amount < Coin value, we can't use this coin to make the change !!! ------------------------------------------------- */ if ( Amount >= v[k] ) { /* ---------------------------------------------------------- Divide step 1. Suppose I USE coin k... ----> 1 coint 2. Then I need to make change for: Amount - v[k] ----> MakeChangeFor(Amount - v[k]) ---------------------------------------------------------- */ sol[k] = MakeChangeFor(Amount - v[k], v); mySol[k] = sol[k] + 1; // 1 is for the coin k that we USE !!! } } /* -------------------------------------------------------- Find the minimum in the mySol[ ] array -------------------------------------------------------- */ myFinalSol = MAX; for ( k = 0; k < C; k++ ) { if ( mySol[k] < myFinalSol ) { myFinalSol = mySol[k]; } } return(myFinalSol); // Return best solution } public static void main(String[] args) { int[] v = {1, 3, 9, 19, 26}; int C, r; Scanner in = new Scanner( System.in ); System.out.print("\nWarning: very slow if change amount > 40 !!!!\n\n\n"); System.out.print("Values of coins: "); for ( int i = 0; i < v.length; i++ ) { System.out.print(v[i] + ", "); } System.out.println("\n"); while ( true ) { System.out.print(" Change amount = "); C = in.nextInt(); r = MakeChangeFor(C, v); System.out.println("Min # coins to make change for " + C + " = " + r); System.out.println("=======================\n"); } } }