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 problem)
For e.g in set 1,10,15,
change for 35 gives–2 coins of 10 and one coin of 15
Also give me an idea of brute forcing algorithm for this. I know to iterate over all the sets. But how to vary the number of each coin while brute forcing
I would think about building the solution one step at a time, inductively:
Coins available are 1c, 5c, 10c, 25c (you can tweak them according to your needs)
If you can formulate the problem inductively, it might be easier to tackle it.
EDIT:
Alright, here’s another attempt to explain the dynamic programming solution:
Think of a table with
xrows (xis number of distinct denominations) andncolumns (nis the amount you have to build using least denominations). Every cell in this table represents a distinct sub-problem and will eventually contain the solution to it. Assume:row 1 represents the set
{1c}i.e. in row 1 you are allowed to use infinite1crow 2 represents the set
{1c, 10c}i.e in row 2 you are allowed to infinite1cand10crow 3 represents the set
{1c, 10c, 15c}and so on…Each column represents the amount you want to construct.
Thus, every cell corresponds to one small sub-problem. For example (the indexes are starting from 1 for the sake of simplicity),
cell(1, 5)==> construct5cusing only{1c}cell(2, 9)==> construct9cusing{1c, 10c}cell(3, 27)==> construct27cusing{1c, 10c, 15c}Now your aim is to get the answer to
cell(x, n)Solution:Start solving the table from the simplest problem. Solving the first row is trivial, since in the first row the only denomination available is
{1c}. Every cell in row 1 has a trivial solution, leading tocell(1, n)={nx1c}(ncoins of1c).Now proceed to the next row. Generalizing for the 2nd row, lets see how to solve for (say)
cell(2, 28)i.e. construct28cusing{1c, 10c}. Here, you need to make a decision, whether to include10cin the solution or not, and how many coins. You have 3 choices (3 = 28/10 + 1)Choice 1:Take
{1x10c}and the rest from the previous row (which is stored incell(1, 18)). This gives you{1x10c, 18x1c}=19 coinsChoice 2:Take
{2x10c}and the rest from previous row (which is stored incell(1, 8)). This gives you{2x10c, 8x1c}=10 coinsChoice 3:Take no
10cand the rest from the previous row (which is stored incell(1, 28)). This gives you{28x1c}=28 coinsClearly, choice 2 is the best as it takes less coins. Write it down in the table and proceed ahead. The table is to be filled one row at a time, and within a row, in the order of increasing amounts.
Going by above rules, you will reach
cell(x, n), the solution to which will be a choice betweenn/p + 1alternatives, wherep= newest denomination in rowx. The best choice is your answer.The table actually memoizes the solutions to smaller problems, so that you don’t need to solve them again and again.