Skip to content

Instantly share code, notes, and snippets.

@thmain
Last active October 26, 2019 00:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save thmain/373370b175d6b0f0d355 to your computer and use it in GitHub Desktop.
Save thmain/373370b175d6b0f0d355 to your computer and use it in GitHub Desktop.
public class MinCoinChange {
public int minCoinDynamic(int amount, int[] coins) {
// this will store the optimal solution
// for all the values -- from 0 to given amount.
int[] coinReq = new int[amount+1];
coinReq[0] = 0; // 0 coins are required to make the change for 0
// now solve for all the amounts
for (int amt = 1; amt <= amount; amt++) {
coinReq[amt] = Integer.MAX_VALUE;
// Now try taking every coin one at a time and pick the minimum
for (int j = 0; j < coins.length; j++) {
if (coins[j] <= amt) { // check if coin value is less than amount
// select the coin and add 1 to solution of (amount-coin value)
coinReq[amt] = Math.min(coinReq[amt - coins[j]] + 1,coinReq[amt]) ;
}
}
}
//return the optimal solution for amount
return coinReq[amount];
}
public static void main(String[] args) {
int[] coins = { 1, 2, 3 };
int amount = 20;
MinCoinChange m = new MinCoinChange();
System.out.println("(Dynamic Programming) Minimum Coins required to make change for "
+ amount + " are: " + m.minCoinDynamic(amount, coins));
}
}
@ShongSu
Copy link

ShongSu commented May 10, 2016

Line 34, should be for(int j=0;j<CC.length;j++){, that is j=0 other than j=1.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment