I want to know the idea of algorithm for the coin change problem where each denomination has infinte number of coins. Means how to apply DP (like the standard coin change pr
Regarding the brute force.
It is called "greedy algorithm" - you always take the biggest coin which is not greater than the value you need to represent.
pseudo code, returns the number of coins needed to represent value, if we can use each one infinite number of times
int[] greedy(int value, int[] coins) {
int[] ans = ...;
int v = coins.length - 1;
int left = value;
while (left > 0 && v >= 0) {
if (coins[v] <= left) {
ans.push(coins[v]);
} else {
v--;
}
}
return left == 0 ? ans : //representation impossible,
//so you better do something;
}
pseudo code, returns the number of coins needed to represent value, if we can use each one infinite number of times
int f(int value, int[] coins) {
int[] memo = new int[value + 1];
Arrays.fill(memo, 1234567);
memo[0] = 0;
for (int coin : coins)
for (int i = 0; i + coin <= value; i++)
memo[i + coin] = min(memo[i + coin], memo[i] + 1);
return memo[value];
}
to know which coins to take, start from the end: if memo[value] = 3
, then you check all coins and find such coin that memo[value - coin] == 2
, continue from (value - coin)
until you reach 0
.