Skip to main content

Knapsack Problem

Definition​

The knapsack (rucksack) problem is about optimizing the selection of items with weights and values to fit within a given limit while maximizing total value. It's named after the challenge of filling a fixed-size knapsack with valuable items. For instance, one version involves choosing boxes to maximize earnings while staying within a weight limit, such as 15 kg. Problem of maximizing the value of items in a knapsack without exceeding its capacity, with items being either selected or not.

0/1 Knapsack Problem

Each item can only be selected once. It involves a set of items with weights wi and values vi, along with a maximum weight capacity W, maximize ∑i=1nvixi\displaystyle\sum_{i = 1}^n v_i x_i subject to ∑i=1nwixi≤W\displaystyle\sum_{i = 1}^n w_i x_i \leq W and xi∈{0,1}x_i \in \{0, 1\} where xix_i signifies the quantity of item i to add to the knapsack. The objective is to maximize the total value of the items while ensuring their combined weight doesn't exceed the knapsack's capacity

Bounded knapsack problem (BKP)

Removes the restriction that there is only one of each item, but restricts the number xix_i of copies of each kind of item to a maximum non-negative integer value c: maximize ∑i=1nvixi\displaystyle\sum_{i = 1}^n v_i x_i subject to ∑i=1nwixi≤W\displaystyle\sum_{i = 1}^n w_i x_i \leq W and 0≤xi≤c0 \leq x_i \leq c

Unbounded knapsack problem (UKP)

Places no upper bound on the number of copies of each kind of item and can be formulated as above except for that the only restriction on xix_i is that it is a non-negative integer, maximize ∑i=1nvixi\displaystyle\sum_{i = 1}^n v_i x_i subject to ∑i=1nwixi≤W\displaystyle\sum_{i = 1}^n w_i x_i \leq W and xi≥0x_i \geq 0

Practice​

knapsack(weights[], values[], capacity):
n = length(weights)
dp = array of size (n + 1) x (capacity + 1) filled with zeros

for i from 1 to n:
for j from 1 to capacity:
if weights[i] <= j:
dp[i][j] = max(dp[i-1][j], dp[i-1][j - weights[i]] + values[i])
else:
dp[i][j] = dp[i-1][j]

return dp[n][capacity]