Knapsack Problem
suggest change0-1 Knapsack
Given items with weights and values, the 0–1 knapsack problem chooses at most one copy of each item. The goal is to maximize total value without exceeding the capacity.
C++ Example:
Implementation:
#include <algorithm>
#include <span>
#include <stdexcept>
#include <vector>
int knapsack(std::span<const int> weights,
std::span<const int> values,
int capacity) {
if (weights.size() != values.size() || capacity < 0)
throw std::invalid_argument("invalid knapsack input");
std::vector<int> best(static_cast<std::size_t>(capacity) + 1);
for (std::size_t item = 0; item < weights.size(); ++item) {
if (weights[item] <= 0)
throw std::invalid_argument("weights must be positive");
for (int limit = capacity; limit >= weights[item]; --limit) {
best[limit] = std::max(
best[limit], best[limit - weights[item]] + values[item]);
}
}
return best[capacity];
}
Test:
3 5
5 2
2 1
3 2
Output:
8
Interpreting each row as (value, weight), the maximum value is 8, achieved by choosing (5, 2) and (3, 2) for a total weight of 4.
Unbounded Knapsack
The unbounded knapsack variant permits any number of copies of each item.
Python 3 example:
Implementation:
def unbounded_knapsack(weights: list[int], values: list[int], capacity: int) -> int:
if len(weights) != len(values) or capacity < 0:
raise ValueError("invalid knapsack input")
best = [0] * (capacity + 1)
for limit in range(1, capacity + 1):
for weight, value in zip(weights, values, strict=True):
if weight <= 0:
raise ValueError("weights must be positive")
if weight > limit:
continue
best[limit] = max(best[limit], value + best[limit - weight])
return best[capacity]
The complexity is O(nC), where n is the number of items and C is the capacity.
Test:
weights = [2, 3, 4, 5, 6]
values = [2, 4, 6, 8, 9]
print(unbounded_knapsack(weights, values, 13))
Output:
20
The maximum value that can be achieved is 20, by taking two copies of the item with weight 5 and value 8, plus the item with weight 3 and value 4.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents