More From This User
logic for computer science - automated theorem proving
logic for computer science - automated theorem proving by Jean H Gallier
Tech Interview
Puzzles and other questions for interviews...
mal substructure in the following manner. Consider any optimal solution to making change forn cents using coins of denominationsd1 ,d2 ,...,dk. Now consider breaking that solution into two di\ufb00erent pieces along any coin boundary. Suppose that the \u201cleft-half\u201d of the solution amounts tob cents and the \u201cright-half\u201d of the solution amounts ton\u2212 b cents, as shown below.
\u201cleft-half\u201d of the optimal solution shown. Then the left-half of the optimal solution could be replaced with this better solution, yielding a valid solution to making change forn cents with fewer coins than the solution being considered. But this contradicts the supposed optimality of the given solution,\u2192\u2190. An identical argument applies to the \u201cright-half\u201d of the solution.
we shall later de\ufb01ne recursively. LetC[p] be the minimum number of coins of denominationsd1 ,d2 ,...,dk needed to make change forp cents. In the optimal solution to making change forp cents, there must exist some \ufb01rst coindi, wheredi\u2264 p. Furthermore, the remaining coins in the optimal solution must themselves be the optimal solution to making change forp\u2212 di cents, since coin changing exhibits optimal substructure as proven above. Thus, ifdi is the \ufb01rst coin in the optimal solution to making change forp cents, then
know which coindi is the \ufb01rst coin in the optimal solution to making change forp cents; however, we may check allk such possibilities (subject to the constraint thatdi\u2264 p), and the value of the optimal solution must correspond to the minimum value of 1 +C[p\u2212 di], by de\ufb01nition. Furthermore, when making change for 0 cents, the value of the optimal solution is clearly 0 coins. We thus have the following recurrence.
forn cents, and this coin in printed in Line 2 during the \ufb01rst pass through thewhile loop. Since our problem exhibits optimal substructure by Claim 1, it must be the case that the solution to the remainingn\u2212 dS[n] cents be optimal as well. By settingn\u2190 n\u2212 d[S[n]] in Line 3, the \ufb01rst coin in such a solution will be printed in the next pass through thewhile loop, and so on. (Properly, one would prove that the sequence of coins output by this procedure is correct by induction, but the above su\ufb03ces as far as I\u2019m concerned.)
Leave a Comment