Solution: Maximum Amount of Gold
Solutions for the Maximum Amount of Gold Problem.
Solution 1: Analyzing the structure of a solution
Instead of solving the original problem, we will check whether it’s possible to fully pack our backpack with the gold bars. Given gold bars of weights (we switched to 0-based indexing) and an integer , is it possible to select a subset of them of total weight ?
Exercise break: Show how to use the solution to this problem to solve the Maximum Amount of Gold Problem.
Assume that it’s possible to fully pack the backpack. There exists a set of total weight . Does it include the last bar of weight ?
Case 1: If , then a backpack of capacity can be fully packed using the first bars.
Case 2: If , then we can remove the bar of weight from the backpack and the remaining bars will have weight . Therefore, a backpack of capacity can be fully packed with the first gold bars.
In both cases, we reduced the problem to essentially the same problem with a smaller number of items and possibly smaller backpack capacity. We therefore consider the variable equal to true if it is possible to fully pack a backpack of capacity using the first bars, and false, otherwise. The analysis of the two cases above leads to the following recurrence relation for ,
Note that the second term in the above formula does not make sense when . Also, true, and false for any . Overall,
...