Dynamic programming solves overlapping subproblems once and stores their values for reuse. The principle of optimality says that the remaining decisions within an optimal solution must solve the corresponding residual subproblem optimally; otherwise replacing them by a better residual solution would improve the original one. Here removing one chosen stamp leaves an optimal way to form the remaining postage.
Let be the minimum number of stamps for total . Since denomination 1 is available, every nonnegative total is reachable. The dynamic programming recurrence isFill the table in increasing order of :Every representation of has a last stamp , so its remaining count is at least . Conversely, appending to an optimal residual representation attains each candidate. Thus the recurrence is exact by the principle of optimality. Worst-case time is , with storage. This is pseudo-polynomial time in the numerical target, rather than polynomial time in its binary encoding length.
F[0] = 0
for x = 1,...,m:
F[x] = infinity
for i = 1,...,n:
if d[i] <= x:
F[x] = min(F[x], 1 + F[x-d[i]])
return F[m]Whenever an update improves , store
choice[x] = i. Starting at x = m, repeatedly increment count[choice[x]] and subtract that denomination from x, stopping at zero. The invariant is that the selected stamps plus an optimal representation of the residual total attain the original optimum; every step reduces by one. Reconstruction uses steps and output counters, preserving the total time bound.The greedy algorithm repeatedly takes the largest denomination no greater than the remaining postage. For denominations and target , it returns , using three stamps. The optimum is , using two. Thus local preference for the largest stamp does not generally solve the coin change problem optimally.
Use greedy coin change for powers of an integer, with integer . In any optimal solution, there can be no or more stamps of denomination for : replacing of them by one stamp preserves value and reduces the stamp count by .
Consequently each lower-denomination count lies in , and their total value is at mostThe number of largest stamps must therefore be , leaving a residual below . Apply the same argument successively to lower powers. This forces exactly the greedy quotients, proving optimality. For , only unit stamps are available and the conclusion is immediate. Integer is essential to the carry argument and follows from the stated integer denominations whenever denomination is present.
Articles by others on the same topic
There are currently no matching articles.