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,
As ranges from to and ranges from to , we have variables. Since depends on , we process all variables in the increasing order of . In the pseudocode below, we use a two-dimensional array pack of size stores the value of . The running time of this solution is .
:
two-dimensional array of size
initialize all elements of to false
true
for from to :
for from to :
if :
else:
return
The two-dimensional table below presents the results of the call to and uses “F” and “T” to denote false and true values.
Level up your interview prep. Join Educative to access 80+ hands-on prep courses.