The knapsack problem is a classic combinatorial optimization problem in which a decision maker selects a subset of items, each with a weight and a value, so that the total value is maximized while the total weight stays within a fixed capacity. In artificial intelligence and operations research, it serves as the canonical model for resource allocation under a budget, from feature selection and compute scheduling to portfolio construction.
The problem is NP-hard in its decision form, yet it is also one of the most tractable hard problems: a pseudo-polynomial dynamic program solves typical instances exactly, and a fully polynomial-time approximation scheme (FPTAS) guarantees near-optimal answers. This dual character makes it a standard teaching example and a frequent subproblem inside larger solvers.
Formal definition of the knapsack problem
The 0-1 knapsack problem is defined by n items, where item i has a weight w_i and a value v_i, and a knapsack with capacity W. Each binary decision variable x_i equals 1 if the item is packed and 0 otherwise. The goal is to maximize the sum of v_i x_i subject to the single linear constraint that the sum of w_i x_i does not exceed W.
Written this way, the knapsack problem is an integer programming problem with one constraint row. Its linear programming relaxation, which allows fractional x_i between 0 and 1, is solved greedily by sorting items by value-to-weight ratio and filling the knapsack until one item must be split. That relaxation supplies the upper bound used by branch and bound methods.
The table below summarizes the elements of the formal model and their role in the optimization.
| Element | Symbol | Role in the model |
|---|---|---|
| Items | i = 1 to n | Candidate choices to include or exclude |
| Weight | w_i | Resource consumed by item i |
| Value | v_i | Benefit gained from item i |
| Capacity | W | Budget limit on total weight |
| Decision variable | x_i in {0, 1} | Whether item i is selected |
| Objective function | max sum of v_i x_i | Total value to maximize |
Main variants and their complexity
Several knapsack variants relax or extend the basic model, and their computational difficulty differs considerably. The fractional knapsack is solvable in O(n log n) time by the greedy ratio rule, while the multidimensional knapsack with several capacity constraints is strongly NP-hard and has no FPTAS unless P equals NP.
The following table compares the most common variants, the restriction each one changes and the best known solution approach.
| Variant | What changes | Typical exact or approximate method |
|---|---|---|
| 0-1 knapsack | Each item taken once or not at all | Dynamic programming, branch and bound |
| Bounded knapsack | Each item has a limited number of copies | Binary splitting into 0-1 items |
| Unbounded knapsack | Unlimited copies of each item | One-dimensional dynamic program |
| Fractional knapsack | Items can be divided | Greedy by value-to-weight ratio |
| Multidimensional knapsack | Several capacity constraints | Mixed-integer solvers, metaheuristics |
| Multiple knapsack | Several knapsacks of given capacity | Branch and bound, Lagrangian bounds |
| Quadratic knapsack | Pairwise value bonuses between items | Semidefinite bounds, heuristics |
Because the 0-1 version can be solved in O(nW) time, it is called weakly NP-hard: running time grows with the numeric size of W rather than with its number of bits. When capacities are very large, such as monetary budgets in cents, the dynamic program becomes impractical and branch and bound or approximation schemes take over.
Solution methods and their trade-offs
Exact and approximate algorithms for the knapsack problem trade optimality guarantees against memory and running time. The dynamic programming table stores the best value achievable for every capacity from 0 to W using the first i items, and the recurrence chooses the better of skipping item i or packing it.
Branch and bound explores a search tree of include and exclude decisions, pruning any node whose relaxation bound cannot beat the incumbent solution. Modern solvers such as the algorithms of Pisinger combine core problem reduction, tight bounds and dynamic programming, and solve instances with tens of thousands of items in fractions of a second.
The table below compares the principal solution strategies.
| Method | Guarantee | Time complexity | Best suited for |
|---|---|---|---|
| Greedy by ratio | At least half of optimum with a simple fix | O(n log n) | Quick baselines |
| Dynamic programming | Exact | O(nW) | Moderate integer capacities |
| Branch and bound | Exact | Exponential worst case | Large n with good bounds |
| FPTAS | Within factor 1 minus epsilon | Polynomial in n and 1/epsilon | Provable near-optimality |
| Metaheuristics | None | User-controlled | Complex multidimensional variants |
The FPTAS works by scaling and rounding item values, then running a dynamic program indexed by value instead of weight. A tolerance of epsilon equal to 0.01 yields a solution within 1 percent of the optimum, at the cost of memory that grows with n squared divided by epsilon.
Where the knapsack problem appears in artificial intelligence
In machine learning practice, the knapsack structure emerges whenever a system must select items under a budget. Examples include choosing features under a measurement cost limit, selecting training examples for active learning under a labeling budget, and assigning requests to accelerators under memory or latency constraints.
- Model compression: choosing which layers to quantize or prune so that accuracy loss is minimized under a size budget.
- Retrieval-augmented generation: packing the most relevant passages into a fixed context window measured in tokens.
- Ad and recommendation allocation: selecting slots that maximize expected revenue within a spending cap.
- Neural combinatorial optimization: training reinforcement learning or graph neural network policies that learn packing heuristics.
The decision table below indicates which method a practitioner should consider in typical situations.
| Situation | Recommended approach | Reason |
|---|---|---|
| Small integer capacity, few thousand items | Dynamic programming | Exact and simple to implement |
| Huge capacity values | Branch and bound or FPTAS | Avoids a table indexed by capacity |
| Several resource limits | Mixed-integer linear programming solver | Handles extra constraints natively |
| Real-time decisions in milliseconds | Greedy with ratio sorting | Fast with acceptable quality |
| Many similar instances in production | Learned heuristic plus repair | Amortizes cost across instances |
Limitations and common mistakes
The most frequent error is treating the greedy ratio heuristic as optimal for the 0-1 case. With capacity 10, an item of weight 6 and value 7 has a better ratio than two items of weight 5 and value 5 each, yet the pair yields value 10 against 7, so pure greedy can be badly suboptimal unless it is compared with the best single item.
- Floating-point weights break the dynamic program, which needs integer capacities; scale and round them deliberately.
- Memory blow-up occurs when the full n by W table is stored; a single array updated in reverse order suffices for the value alone.
- Ignoring correlated data: instances where value is strongly correlated with weight are much harder for branch and bound.
- Overlooking side constraints such as item conflicts, which turn the model into a different problem.
Understanding it simply
Imagine packing a backpack for a hike. Each item has a weight and a usefulness. The bag can only hold so much. You want the most useful load that still fits.
That is the knapsack problem. With a few items, you can try every combination. With hundreds, the combinations explode. Computers therefore use clever shortcuts and exact tables to find the best choice quickly. The key lesson is simple: taking the best item first is not always best overall.
Applied in practice
A team building a retrieval-augmented assistant must fit retrieved documents into a prompt limited to 4,000 tokens after instructions. A search step returns 40 candidate passages, each with a token length and a relevance score from a reranking model. Simply taking the top-ranked passages in order often wastes space, because one long passage can block two shorter ones that together are more relevant.
The engineers model the selection as a 0-1 knapsack problem: token length is the weight, relevance is the value, and the budget is the capacity. A dynamic program over 40 items and 4,000 tokens runs in about 160,000 steps, well under a millisecond. In offline evaluation, the packed contexts answered more questions correctly than top-k truncation, and latency stayed unchanged.