Knapsack problem

On this page 7

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.

ElementSymbolRole in the model
Itemsi = 1 to nCandidate choices to include or exclude
Weightw_iResource consumed by item i
Valuev_iBenefit gained from item i
CapacityWBudget limit on total weight
Decision variablex_i in {0, 1}Whether item i is selected
Objective functionmax sum of v_i x_iTotal value to maximize
Components of the 0-1 knapsack model

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.

VariantWhat changesTypical exact or approximate method
0-1 knapsackEach item taken once or not at allDynamic programming, branch and bound
Bounded knapsackEach item has a limited number of copiesBinary splitting into 0-1 items
Unbounded knapsackUnlimited copies of each itemOne-dimensional dynamic program
Fractional knapsackItems can be dividedGreedy by value-to-weight ratio
Multidimensional knapsackSeveral capacity constraintsMixed-integer solvers, metaheuristics
Multiple knapsackSeveral knapsacks of given capacityBranch and bound, Lagrangian bounds
Quadratic knapsackPairwise value bonuses between itemsSemidefinite bounds, heuristics
Common knapsack variants

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.

MethodGuaranteeTime complexityBest suited for
Greedy by ratioAt least half of optimum with a simple fixO(n log n)Quick baselines
Dynamic programmingExactO(nW)Moderate integer capacities
Branch and boundExactExponential worst caseLarge n with good bounds
FPTASWithin factor 1 minus epsilonPolynomial in n and 1/epsilonProvable near-optimality
MetaheuristicsNoneUser-controlledComplex multidimensional variants
Knapsack solution strategies compared

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.

SituationRecommended approachReason
Small integer capacity, few thousand itemsDynamic programmingExact and simple to implement
Huge capacity valuesBranch and bound or FPTASAvoids a table indexed by capacity
Several resource limitsMixed-integer linear programming solverHandles extra constraints natively
Real-time decisions in millisecondsGreedy with ratio sortingFast with acceptable quality
Many similar instances in productionLearned heuristic plus repairAmortizes cost across instances
Choosing a method for a knapsack instance

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.