/* ============================================== Simplified coin change program Fixed coin values: {1, 3, 5, 8} ============================================== */ import java.util.Scanner; public class Coins { static int MakeChangeFor(int Amount) { int[] helpSol = new int[4]; // Solutions of smaller problems // for each of the 4 different coin values int mySol; for (int k = 0; k < 4; k++ ) { helpSol[k] = Integer.MAX_VALUE-2; } /* ---------------------------------- Base case: make change for $0 ---------------------------------- */ if ( Amount == 0 ) { return(0); } else { /* -------------------------------------------------------- Suppose I use coin #1 -------------------------------------------------------- */ if ( Amount >= 1 ) // Coin 1 has value 1 { // Suppose I use coin #1 to make the change.... // Then I still need to make change for Amount-1 helpSol[0] = MakeChangeFor(Amount-1); // Let someone solve the smaller problem Amount-1 } if ( Amount >= 3 ) // Coin 2 has value 3 { // Suppose I use coin #2 to make the change.... // Then I still need to make change for Amount-3 helpSol[1] = MakeChangeFor(Amount-3); // Let someone solve the smaller problem Amount-3 } if ( Amount >= 5 ) // Coin 3 has value 5 { // Suppose I use coin #3 to make the change.... // Then I still need to make change for Amount-5 helpSol[2] = MakeChangeFor(Amount-5); // Let someone solve the smaller problem Amount-5 } if ( Amount >= 8 ) // Coin 4 has value 8 { // Suppose I use coin #4 to make the change.... // Then I still need to make change for Amount-8 helpSol[3] = MakeChangeFor(Amount-8); // Let someone solve the smaller problem Amount-8 } // Find the SMALLEST # coins I need to use // This is the "find min" algorithm mySol = helpSol[0] + 1; for ( int k = 1; k < 4; k++ ) { if ( helpSol[k] + 1 < mySol ) { mySol = helpSol[k] + 1; // I found a better solution } } } return(mySol); // Return best solution !!! } public static void main(String[] args) { Scanner in = new Scanner( System.in ); int C, r; System.out.print("\nWarning: very slow if change amount > 50 !\n"); System.out.print("\nGood value: 39\n\n"); while ( true ) { System.out.println("=============================================\n"); System.out.println(" Values of coins: {coin1=1, coin2=3, coin3=5, coin4=8}\n"); System.out.print(" Change amount = "); C = in.nextInt(); r = MakeChangeFor(C); System.out.println(" Min # coins to make change for "+C+" = "+r+"\n"); } } }