Knapsack problem

Posted on March 27, 2015

There are two forms of the Knapsack problem, one is the \(0-1\) knapsack problem and fractional knapsack problem. The \(0-1\) knapsack problem is a widely used counter-example that the greedy strategy wouldn’t always work, while the fractional knapsack problem has a greedy solution.

\(0-1\) Knapsack problem

There are \(n\) items and the \(i\)th item is worth \(v_i\) dollars and weights \(w_i\) pounds (\(v_i\) and \(w_i\) are integers). You cannot carry more than \(W\) weight in the Knapsack, where \(W\) is also an integer. The problem is to find out what items one should take.

One can use dynamic programming to solve the \(0-1\) Knapsack problem and also construct an easy counterexample to show that the greedy strategy can fail in this case. The dynamic programming algorithm takes \(O(nW)\) time.

Fractional Knapsack problem

The setup for this is the same as \(0-1\) Knapsack problem, but in this case we can take a fraction of the item too.

Algorithm

The algorithm is as follows

The above algorithm is, of course, greedy (this algorithm fails for the \(0-1\) knapsack problem). The running time of the algorithm is \(\mathcal O (n^2)\).

Notes