Skip to content

Instantly share code, notes, and snippets.

@yokolet
Last active March 29, 2017 04:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yokolet/1342734afc4cdc4c2e3a0b99e6e582d2 to your computer and use it in GitHub Desktop.
Save yokolet/1342734afc4cdc4c2e3a0b99e6e582d2 to your computer and use it in GitHub Desktop.
/*
Problem: Given denominators (coins) and an amount,
find minimum number of coins to make the amount.
*/
public class CoinChangeMin {
// complexity: time exponential
static int findMinCoinsRecur(int[] coins, int n, int S) {
// base case, amount = 0
if (S == 0) {
return 0;
}
int result = Integer.MAX_VALUE;
for (int i=0; i<n; i++) {
if (coins[i] <= S) {
int temp = findMinCoinsRecur(coins, n, S-coins[i]);
if (temp != Integer.MAX_VALUE &&
temp + 1 < result) {
result = temp + 1;
}
}
}
return result;
}
// complexity: time O(n*m), space O(m), n: number of coins, m: sum
static int findMinCoins(int[] coins, int S) {
int[] memo = new int[S + 1];
// initialize
for (int i=1; i<memo.length; i++) { memo[i] = Integer.MAX_VALUE; }
for (int i=1; i<=S; i++) {
for (int j=0; j<coins.length; j++) {
if (coins[j] <= i && (memo[i-coins[j]] + 1 < memo[i])) {
memo[i] = memo[i-coins[j]] + 1;
}
}
}
return memo[S];
}
public static void main(String[] args) {
int[] coins = {1, 3, 5};
int S = 11;
System.out.println(findMinCoinsRecur(coins, coins.length, S));
System.out.println(findMinCoins(coins, S));
}
}
/*
References:
http://algorithms.tutorialhorizon.com/dynamic-programming-minimum-coin-change-problem/
http://www.geeksforgeeks.org/find-minimum-number-of-coins-that-make-a-change/
http://www.programcreek.com/2015/04/leetcode-coin-change-java/
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment