I’ve been reviewing some dynamic programming problems, and I have had hard time wrapping my head around some code in regards to finding the smallest number of coins to make change.
Say we have coins worth 25, 10, and 1, and we are making change for 30. Greedy would return 25 and 5(1) while the optimal solution would return 3(10). Here is the code from the book on this problem:
def dpMakeChange(coinValueList,change,minCoins):
for cents in range(change+1):
coinCount = cents
for j in [c for c in coinValueList if c <= cents]:
if minCoins[cents-j] + 1 < coinCount:
coinCount = minCoins[cents-j]+1
minCoins[cents] = coinCount
return minCoins[change]
If anyone could help me wrap my head around this code (line 4 is where I start to get confused), that would be great. Thanks!
It looks to me like the code is solving the problem for every cent value up until target cent value. Given a target value
vand a set of coinsC, you know that the optimal coin selectionShas to be of the formunion(S', c), wherecis some coin fromCandS'is the optimal solution forv - value(c)(excuse my notation). So the problem has optimal substructure. The dynamic programming approach is to solve every possible subproblem. It takescents * size(C)steps, as opposed to something that blows up much more quickly if you just try to brute force the direct solution.