0-1 Knapsack

To showcase a dynamic programming solution, exploring the properties of the problem that make it solvable by this technique, we shall look at the 0-1 knapsack problem.

You are given weights and values of n items. You must put these items in a knapsack of capacity W to get the maximum value of the knapsack. You cannot break an item. You can either pick it or not pick it (hence the 0-1 property).

In other words, you are given two arrays, values[0...n-1] and weights[0...n-1], which represent values and weights associated with n items, respectively. You want to find the maximum value subset of values[] such that the sum of weights of the subset is smaller than or equal to W.

The first immediate solution to this problem is to consider all subsets of items and calculate the total weight and value of all subsets, considering only those whose total weight is smaller than W. To consider all subsets of items, we can observe that there are two choices for each item: either it is included in the optimal subset, or it is not. Hence, the maximum value we can obtain from n items is the maximum of two values:

  1. The maximum value obtained by n-1 items and W weight (that is, they don't include the nth item in the optimal solution)
  2. The value of the nth item plus the maximum value obtained by n-1 items and W minus the weight of the nth item (for example, including the nth item)

With the previous observation, we've shown the optimal substructure property for the 0-1 knapsack problem.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.135.216.75