Skip to content

Latest commit

 

History

History
1110 lines (706 loc) · 30 KB

12-knapsack-problem.md

File metadata and controls

1110 lines (706 loc) · 30 KB

Integer Linear Programming Notes 12: Knapsack Problem

Author: Hang Li (@flgkd)

Note: Titles marked with ⭐ highlight key concepts and important summaries.

1. Preface

This note studies the knapsack problem, one of the most classical problems in combinatorial optimization and integer programming.

This note is primarily based on Sun and Li's Integer Programming [1], together with standard references on knapsack problems [2,3].

The knapsack problem is important for at least three reasons:

  1. it is a standard model for resource allocation under capacity constraints;
  2. it is a central example in dynamic programming;
  3. it plays an important role in computational complexity theory.

A point that should be stated carefully is the following:

For the standard 0-1 knapsack problem with binary-encoded integer data, the decision version is NP-complete, while the optimization version is NP-hard [3].

So when people casually say that “the knapsack problem is NP-complete,” they are normally referring to the standard decision form, not the optimization problem itself.

This note mainly focuses on several standard variants:

  • 0-1 knapsack;
  • unbounded / complete knapsack;
  • bounded knapsack;
  • grouped knapsack.

Since the previous note already introduced the general idea of dynamic programming, this note will emphasize how those ideas are specialized to knapsack-type models.

For a review of dynamic programming, see:

For a review of complexity issues such as NP-completeness and pseudo-polynomial time, see:


2. Introduction to the Knapsack Problem⭐⭐⭐

2.1 Basic Description

In its most intuitive form, the knapsack problem asks:

Given a set of items, each with a weight (or volume) and a value, how should we choose items so that the total weight does not exceed the capacity of the knapsack and the total value is as large as possible?

This is a maximization problem under a capacity constraint.

The name comes from the physical interpretation of selecting the most valuable collection of items that can fit into a capacity-limited knapsack. Knapsack-type models and closely related subset-selection problems appear in resource allocation, combinatorial optimization, computational complexity, and applied mathematics [2,3]. They also appeared historically in public-key cryptographic constructions, notably the Merkle-Hellman trapdoor-knapsack scheme [4].

A standard 0-1 formulation is

$$ \max \quad \sum_{j=1}^{n}c_jx_j $$

subject to

$$ \sum_{j=1}^{n}a_jx_j\le B $$

$$ x_j\in{0,1},\quad j=1,\ldots,n. $$

Here:

  • $a_j$ is the weight / volume of item $j$;
  • $c_j$ is the value / profit of item $j$;
  • $B$ is the capacity of the knapsack;
  • $x_j=1$ means item $j$ is selected, and $x_j=0$ means it is not selected.

2.2 Optimization Form vs. Decision Form

The optimization form asks for the maximum achievable value.

The corresponding decision form asks:

Is there a feasible selection whose total weight is at most $B$ and whose total value is at least some target value $V$?

This distinction is important in complexity theory:

  • the decision version is NP-complete;
  • the optimization version is NP-hard.

2.3 Why Dynamic Programming Applies

The knapsack problem is a very typical dynamic programming (DP) problem.

Its structure is suitable for DP because:

  1. we need to consider all feasible possibilities while still computing the true optimum;
  2. many subproblems repeat, so intermediate results should be stored;
  3. the problem can be decomposed into smaller subproblems through a state transition equation.

The key structural property is optimal substructure. This state-based recursive viewpoint is part of the classical dynamic-programming framework developed by Bellman [5].

In practice, for a dynamic-programming formulation, the most important tasks are:

  1. defining the state clearly;
  2. describing the optimal substructure;
  3. deriving the recurrence relation.

2.4 Integer Capacity and Weight Requirement of the Classical DP⭐⭐⭐

The classical knapsack dynamic program used throughout this note takes the capacity as a state index:

$$ j=0,1,\ldots,V. $$

Therefore, the standard $O(NV)$ capacity-indexed formulation assumes that the item volumes / weights and the knapsack capacity are integer-valued, or can be scaled to integers:

$$ v_i\in\mathbb{Z}_{>0},\quad V\in\mathbb{Z}_{\ge0}. $$

This integer requirement comes from the state space, not from the objective values.

The item values $w_i$ do not need to be integers for the recurrence itself. For example, values such as

$$ w=(3.7,5.2,8.6) $$

cause no difficulty, because the values are stored in the DP table rather than used as array indices.

The important distinction is:

The quantity used as the DP index must be discretely enumerable. In the classical capacity-indexed knapsack DP, that quantity is the weight / capacity.

The Python implementations in this note read integer inputs for simplicity, but mathematically the value coefficients may be real numbers.

What If the Weights or Capacity Are Not Integers?

The knapsack problem itself does not require integer weights. What changes is whether the classical capacity-indexed DP can be used directly.

There are several common cases.

Case 1: Finite Decimal or Rational Weights

If all weights and the capacity have a common finite precision, multiply them by a common scaling factor.

For example,

$$ v=(1.2,2.7,3.5),\quad V=5.4 $$

can be multiplied by $10$ to obtain

$$ v'=(12,27,35),\quad V'=54. $$

The ordinary integer-capacity DP can then be applied exactly.

More generally, rational weights can be multiplied by a common denominator.

However, scaling may make the capacity very large. If the original data have many decimal places, the scaled value $V'$ may become so large that an $O(NV')$ algorithm is no longer practical.

Case 2: Integer Values but Non-Integer Weights

If the values $w_i$ are nonnegative integers, the roles of weight and value can sometimes be reversed.

Define

$$ g(i,p)=\text{minimum total weight required to obtain total value }p\text{ using the first }i\text{ items}. $$

For the 0-1 problem, initialize

$$ g(0,0)=0 $$

and

$$ g(0,p)=+\infty,\quad p>0. $$

For $p\ge w_i$, the recurrence is

$$ g(i,p)=\min{g(i-1,p),g(i-1,p-w_i)+v_i}. $$

For $p<w_i$,

$$ g(i,p)=g(i-1,p). $$

The weights $v_i$ may now be non-integers because they are stored as DP values rather than used as state indices.

After computing states for $p=0,1,\ldots,\sum_{i=1}^{N}w_i$, the optimal value is the largest $p$ satisfying

$$ g(N,p)\le V. $$

This is a value-indexed dynamic program rather than a capacity-indexed one. Its running time is $O(NP)$, where $P=\sum_{i=1}^{N}w_i$, so it is pseudo-polynomial in the total integer value [3].

Case 3: General Real-Valued Data

If neither the weights nor the values admit a useful discrete scaling, one can no longer rely on the simple $O(NV)$ table.

Possible approaches include:

  • maintaining only nondominated $(\text{weight},\text{value})$ states;
  • solving the problem directly as a mixed-integer linear program;
  • using branch-and-bound or branch-and-cut;
  • using approximation algorithms when an exact solution is unnecessary.

In a nondominated-state method, state $(W_1,P_1)$ dominates state $(W_2,P_2)$ if

$$ W_1\le W_2 $$

and

$$ P_1\ge P_2, $$

with at least one strict inequality. The dominated state $(W_2,P_2)$ can then be discarded because it uses no less weight and provides no greater value.

Such methods can handle non-integer weights, although the number of nondominated states may grow exponentially in the worst case [3].

One special situation is also worth noting. If all item weights are integers but the capacity is not, for example

$$ V=10.7, $$

then every feasible total weight is integer, so the constraint is equivalent to using

$$ \lfloor V\rfloor=10. $$

In summary:

integer / discretized weights and capacity
→ classical capacity-indexed DP
→ O(NV)

finite decimals or rational weights
→ scale to integers
→ exact DP, but the scaled capacity may become large

integer values but non-integer weights
→ value-indexed DP may be possible

general real-valued data
→ sparse-state DP, MILP, branch-and-bound, or approximation methods

3. 0-1 Knapsack Problem⭐⭐⭐

3.1 Problem Description

There are $N$ items and a knapsack with capacity $V$.

Each item can be used at most once.

The volume of item $i$ is $v_i$, and its value is $w_i$. For the capacity-indexed DP used below, assume $v_i$ and $V$ are integers; $w_i$ does not need to be integer.

We want to select a subset of items so that:

  • the total volume does not exceed $V$;
  • the total value is maximized.

3.2 State Definition and Recurrence

Let

$$ f(i,j) $$

denote the maximum total value obtainable by choosing from the first $i$ items with total volume not exceeding $j$.

Then the state transition is

$$ f(i,j)=\max{f(i-1,j),f(i-1,j-v_i)+w_i}, \qquad j\ge v_i. $$

If $j<v_i$, then item $i$ cannot be taken, so

$$ f(i,j)=f(i-1,j). $$

A useful way to understand the state $f(i,j)$ is to separate its set and property.

The set represented by $f(i,j)$ contains all feasible selections satisfying two conditions:

  1. items are chosen only from the first $i$ items;
  2. the total volume does not exceed $j$.

The property stored for this set is the maximum total value. In other dynamic-programming problems, the stored property could instead be a minimum value, a count, or another quantity.

To derive the state transition, partition the feasible selections into two disjoint cases according to whether item $i$ is selected.

If item $i$ is not selected, the best value is

$$ f(i-1,j). $$

If item $i$ is selected, then $j\ge v_i$, and after reserving volume $v_i$ for item $i$, the remaining problem uses only the first $i-1$ items. The best value is therefore

$$ f(i-1,j-v_i)+w_i. $$

Taking the better of these two cases gives

$$ f(i,j)=\max{f(i-1,j),f(i-1,j-v_i)+w_i},\quad j\ge v_i. $$

So every state is obtained by a simple set partition:

all feasible selections represented by f(i,j)
        ↓
exclude item i        include item i
        ↓                    ↓
f(i-1,j)       f(i-1,j-v_i) + w_i

This “define the state set → identify the stored property → partition the set” viewpoint is a useful general method for constructing dynamic-programming recurrences.

3.3 Naive Dynamic-Programming Algorithm

The direct 2D dynamic program is:

import sys


def solve() -> None:
    data = sys.stdin.read().strip().split()
    if not data:
        return

    it = iter(map(int, data))
    n = next(it)
    m = next(it)

    v = [0] * (n + 1)
    w = [0] * (n + 1)
    for i in range(1, n + 1):
        v[i] = next(it)
        w[i] = next(it)

    f = [[0] * (m + 1) for _ in range(n + 1)]

    for i in range(1, n + 1):
        for j in range(m + 1):
            f[i][j] = f[i - 1][j]
            if j >= v[i]:
                f[i][j] = max(f[i][j], f[i - 1][j - v[i]] + w[i])

    print(f[n][m])


if __name__ == "__main__":
    solve()

The time complexity is

$$ O(NV), $$

and the space complexity is also

$$ O(NV). $$

3.4 Space Optimization⭐

The 2D recurrence only uses the previous row, so we can reduce the state dimension from 2D to 1D.

Let

$$ f(j) $$

be the best value for capacity $j$ after processing some prefix of items.

Suppose the first $i-1$ items have already been processed. Before item $i$ is updated, the current array entry $f(j)$ represents the old state $f(i-1,j)$.

Therefore:

  1. the term $f(i-1,j)$ is already stored in $f(j)$, so copying it explicitly is unnecessary;
  2. the transition involving item $i$ only needs to be considered when $j\ge v_i$, so the capacity loop can start from $v_i$;
  3. the remaining candidate is obtained from $f(j-v_i)+w_i$.

This gives the compressed transition

$$ f(j)=\max{f(j),f(j-v_i)+w_i}. $$

However, after compression, the order of the capacity loop is crucial.

For 0-1 knapsack, we must traverse $j$ from large to small:

import sys


def solve() -> None:
    data = sys.stdin.read().strip().split()
    if not data:
        return

    it = iter(map(int, data))
    n = next(it)
    m = next(it)

    v = [0] * (n + 1)
    w = [0] * (n + 1)
    for i in range(1, n + 1):
        v[i] = next(it)
        w[i] = next(it)

    f = [0] * (m + 1)

    for i in range(1, n + 1):
        for j in range(m, v[i] - 1, -1):
            f[j] = max(f[j], f[j - v[i]] + w[i])

    print(f[m])


if __name__ == "__main__":
    solve()

Why must the loop go from large to small?

Because we need the transition to use the value from the previous layer:

$$ f(i-1,j-v_i), $$

not the already updated current-layer value.

If we loop $j$ from small to large, then $f(j-v_i)$ may already have been updated using item $i$, which would incorrectly allow item $i$ to be used multiple times.

So for 0-1 knapsack:

Descending capacity order ensures that each item is used at most once.


4. Unbounded / Complete Knapsack Problem⭐⭐⭐

4.1 Problem Description

There are $N$ types of items and a knapsack with capacity $V$.

Each type of item can be used infinitely many times.

The volume of item type $i$ is $v_i$, and its value is $w_i$. For the capacity-indexed DP used below, assume $v_i$ and $V$ are integers; $w_i$ does not need to be integer.

We want to maximize the total value subject to the capacity constraint.

4.2 State Definition and Naive Recurrence

Let

$$ f(i,j) $$

denote the maximum value obtainable by using the first $i$ item types with total volume not exceeding $j$.

Then the most direct recurrence is

$$ f(i,j)=\max_{0\le k\le\lfloor j/v_i\rfloor}{f(i-1,j-kv_i)+kw_i}. $$

This means that for item type $i$, we may choose:

  • $0$ copies,
  • $1$ copy,
  • $2$ copies,
  • and so on,

as long as the total volume remains feasible.

4.3 Naive Dynamic-Programming Algorithm

import sys


def solve() -> None:
    data = sys.stdin.read().strip().split()
    if not data:
        return

    it = iter(map(int, data))
    n = next(it)
    m = next(it)

    v = [0] * (n + 1)
    w = [0] * (n + 1)
    for i in range(1, n + 1):
        v[i] = next(it)
        w[i] = next(it)

    f = [[0] * (m + 1) for _ in range(n + 1)]

    for i in range(1, n + 1):
        for j in range(m + 1):
            k = 0
            while k * v[i] <= j:
                f[i][j] = max(f[i][j], f[i - 1][j - k * v[i]] + k * w[i])
                k += 1

    print(f[n][m])


if __name__ == "__main__":
    solve()

The time complexity is

$$ O(NV\max_i{V/v_i}), $$

which is often written more simply as a three-loop dynamic program.

4.4 First Optimization: A Better Recurrence⭐

The naive recurrence can be rewritten more efficiently.

Expand the formula:

$$ f(i,j)=\max{f(i-1,j),f(i-1,j-v_i)+w_i,f(i-1,j-2v_i)+2w_i,\ldots}. $$

Now consider

$$ f(i,j-v_i)+w_i. $$

Using the definition of $f(i,j-v_i)$, this becomes

$$ \max{f(i-1,j-v_i)+w_i,f(i-1,j-2v_i)+2w_i,\ldots}. $$

Therefore we obtain the important simplified recurrence:

$$ f(i,j)=\max{f(i-1,j),f(i,j-v_i)+w_i}, \qquad j\ge v_i. $$

This is the key difference from 0-1 knapsack.

Here the second term uses

$$ f(i,j-v_i), $$

not

$$ f(i-1,j-v_i). $$

This reflects the fact that item type $i$ may be used repeatedly.

4.5 First Optimized 2D Algorithm

import sys


def solve() -> None:
    data = sys.stdin.read().strip().split()
    if not data:
        return

    it = iter(map(int, data))
    n = next(it)
    m = next(it)

    v = [0] * (n + 1)
    w = [0] * (n + 1)
    for i in range(1, n + 1):
        v[i] = next(it)
        w[i] = next(it)

    f = [[0] * (m + 1) for _ in range(n + 1)]

    for i in range(1, n + 1):
        for j in range(m + 1):
            f[i][j] = f[i - 1][j]
            if j >= v[i]:
                f[i][j] = max(f[i][j], f[i][j - v[i]] + w[i])

    print(f[n][m])


if __name__ == "__main__":
    solve()

4.6 Second Optimization: 1D DP⭐

The same idea can be compressed into 1D.

Now the capacity loop must go from small to large:

import sys


def solve() -> None:
    data = sys.stdin.read().strip().split()
    if not data:
        return

    it = iter(map(int, data))
    n = next(it)
    m = next(it)

    v = [0] * (n + 1)
    w = [0] * (n + 1)
    for i in range(1, n + 1):
        v[i] = next(it)
        w[i] = next(it)

    f = [0] * (m + 1)

    for i in range(1, n + 1):
        for j in range(v[i], m + 1):
            f[j] = max(f[j], f[j - v[i]] + w[i])

    print(f[m])


if __name__ == "__main__":
    solve()

Why ascending order this time?

Because we want the transition to use the current-layer value

$$ f(i,j-v_i), $$

which already accounts for the possibility of using item type $i$ multiple times.

So for complete knapsack:

Ascending capacity order allows an item type to be reused.


5. Bounded Knapsack Problem⭐⭐⭐

5.1 Problem Description

There are $N$ types of items and a knapsack with capacity $V$.

Item type $i$ has:

  • volume $v_i$,
  • value $w_i$,
  • quantity limit $s_i$.

For the capacity-indexed DP used below, assume $v_i$ and $V$ are integers. The value $w_i$ may be non-integer, while $s_i$ is naturally a nonnegative integer.

We want to maximize total value subject to the capacity constraint.

5.2 State Definition and Naive Recurrence

Let

$$ f(i,j) $$

denote the maximum value obtainable by using the first $i$ item types with total volume not exceeding $j$.

Then the direct recurrence is

$$ f(i,j)=\max_{0\le k\le\min(s_i,\lfloor j/v_i\rfloor)}{f(i-1,j-kv_i)+kw_i}. $$

This is almost the same as the complete knapsack recurrence, except that now the number of copies is limited by $s_i$.

5.3 Naive Dynamic-Programming Algorithm

import sys


def solve() -> None:
    data = sys.stdin.read().strip().split()
    if not data:
        return

    it = iter(map(int, data))
    n = next(it)
    m = next(it)

    v = [0] * (n + 1)
    w = [0] * (n + 1)
    s = [0] * (n + 1)
    for i in range(1, n + 1):
        v[i] = next(it)
        w[i] = next(it)
        s[i] = next(it)

    f = [[0] * (m + 1) for _ in range(n + 1)]

    for i in range(1, n + 1):
        for j in range(m + 1):
            k = 0
            while k <= s[i] and k * v[i] <= j:
                f[i][j] = max(f[i][j], f[i - 1][j - k * v[i]] + k * w[i])
                k += 1

    print(f[n][m])


if __name__ == "__main__":
    solve()

5.4 Why the Complete-Knapsack Optimization Does Not Directly Work

At first glance, the multiple knapsack problem looks very similar to the complete knapsack problem, so one may try to reuse the recurrence

$$ f(i,j)=\max{f(i-1,j),f(i,j-v_i)+w_i}. $$

But this is generally not valid.

The reason is that in the complete knapsack problem, item type $i$ may be chosen arbitrarily many times, so the recursive expansion is consistent.

In the bounded knapsack problem, however, the number of copies of type $i$ is capped at $s_i$. The direct recurrence contains only the terms corresponding to

$$ k=0,1,\ldots,s_i $$

subject to the capacity limit.

If we try to use $f(i,j-v_i)+w_i$, its expansion shifts the copy count upward by one. Whenever the capacity is large enough, this expression may contain a candidate corresponding to

$$ k=s_i+1, $$

which violates the quantity limit.

Therefore, repeated reuse of the current-layer state $f(i,j-v_i)$ is valid for complete knapsack but not for bounded knapsack in general.

So the complete-knapsack simplification does not preserve the quantity limit.

5.5 Binary Splitting Optimization⭐⭐⭐

A standard optimization is to transform the bounded problem into a 0-1 knapsack problem by binary decomposition [2,3].

Suppose type $i$ has $s_i$ copies.

We split these copies into groups of sizes

$$ 1,2,4,8,\dots $$

until the remaining number is smaller than the next power of two.

For example, if $s_i=13$, we can split it as

$$ 13=1+2+4+6. $$

The important point is not that $13$ itself is being written in its ordinary binary representation. Rather, the copies are partitioned into bundles whose sizes are powers of two, together with one final remainder bundle.

With the bundle sizes $1,2,4,6$, every integer number of copies from $0$ through $13$ can be represented by selecting an appropriate subset of the bundles. Thus the decision “how many copies of type $i$ should be taken?” can be replaced by several independent take-or-not-take decisions.

Each group becomes an artificial 0-1 item:

  • group size $k$ has volume $k v_i$;
  • group size $k$ has value $k w_i$.

Then choosing a subset of these artificial items is equivalent to choosing any number from $0$ to $s_i$ copies of the original item type.

So the bounded knapsack problem becomes a 0-1 knapsack problem after decomposition.

If $s_{\max}=\max_i s_i$, the straightforward bounded-knapsack implementation is often summarized by the upper bound

$$ O(NVs_{\max}). $$

After binary splitting, item type $i$ produces only $O(\log(s_i+1))$ artificial 0-1 items, giving

$$ O(V\sum_{i=1}^{N}\log(s_i+1)) $$

time for the resulting 0-1 dynamic program.

5.6 Binary-Optimized Algorithm

import sys


def solve() -> None:
    data = sys.stdin.read().strip().split()
    if not data:
        return

    it = iter(map(int, data))
    n = next(it)
    m = next(it)

    items = []
    for _ in range(n):
        a = next(it)  # volume
        b = next(it)  # value
        s = next(it)  # quantity

        k = 1
        while k <= s:
            items.append((k * a, k * b))
            s -= k
            k <<= 1
        if s > 0:
            items.append((s * a, s * b))

    f = [0] * (m + 1)

    for vol, val in items:
        for j in range(m, vol - 1, -1):
            f[j] = max(f[j], f[j - vol] + val)

    print(f[m])


if __name__ == "__main__":
    solve()

6. Grouped / Multiple-Choice Knapsack Problem⭐⭐⭐

6.1 Problem Description

There are $N$ groups of items and a knapsack with capacity $V$.

Each group contains several candidate items, and at most one item may be selected from each group.

This is the grouped form used in this note and is closely related to the multiple-choice knapsack problem (MCKP) [3]. Some MCKP formulations require exactly one item from each group; the at-most-one version can be represented in that form by adding a zero-volume, zero-value dummy item to every group.

If item $k$ in group $i$ is chosen, its volume is $v_{ik}$ and its value is $w_{ik}$.

For the capacity-indexed DP used below, assume the item volumes $v_{ik}$ and the capacity $V$ are integers. The values $w_{ik}$ do not need to be integers.

We want to maximize total value subject to the capacity constraint.

6.2 State Definition and Recurrence

Let

$$ f(i,j) $$

denote the maximum value obtainable from the first $i$ groups with total volume not exceeding $j$.

Then the recurrence is

$$ f(i,j)=\max{f(i-1,j),\max_{1\le k\le s_i,;v_{ik}\le j}{f(i-1,j-v_{ik})+w_{ik}}}, $$

where $s_i$ is the number of items in group $i$.

The first term corresponds to choosing nothing from group $i$.

The inner maximization corresponds to choosing one specific item from group $i$.

So for each group, we choose at most one item.

6.3 Naive Dynamic-Programming Algorithm

import sys


def solve() -> None:
    data = sys.stdin.read().strip().split()
    if not data:
        return

    it = iter(map(int, data))
    n = next(it)
    m = next(it)

    groups = [[] for _ in range(n + 1)]
    for i in range(1, n + 1):
        s = next(it)
        for _ in range(s):
            vol = next(it)
            val = next(it)
            groups[i].append((vol, val))

    f = [[0] * (m + 1) for _ in range(n + 1)]

    for i in range(1, n + 1):
        for j in range(m + 1):
            f[i][j] = f[i - 1][j]
            for vol, val in groups[i]:
                if j >= vol:
                    f[i][j] = max(f[i][j], f[i - 1][j - vol] + val)

    print(f[n][m])


if __name__ == "__main__":
    solve()

6.4 1D Space Optimization

The grouped knapsack problem can also be compressed to 1D.

The key point is the same as in 0-1 knapsack:

The capacity index must be scanned from large to small, so that the values used by the current group still come from the previous group.

Each group should be treated as one DP stage. If the capacity were scanned from small to large, a state already updated using one item from the current group could be reused when considering another item from that same group, which could incorrectly select more than one item from the group.

import sys


def solve() -> None:
    data = sys.stdin.read().strip().split()
    if not data:
        return

    it = iter(map(int, data))
    n = next(it)
    m = next(it)

    groups = []
    for _ in range(n):
        s = next(it)
        group = []
        for _ in range(s):
            vol = next(it)
            val = next(it)
            group.append((vol, val))
        groups.append(group)

    f = [0] * (m + 1)

    for group in groups:
        for j in range(m, -1, -1):
            for vol, val in group:
                if j >= vol:
                    f[j] = max(f[j], f[j - vol] + val)

    print(f[m])


if __name__ == "__main__":
    solve()

7. Comparing the Four Variants⭐⭐⭐

A useful summary is the following.

Variant Item availability State transition idea Capacity loop direction in 1D DP
0-1 knapsack each item at most once take / do not take descending
unbounded / complete knapsack unlimited copies reuse current item type ascending
bounded knapsack limited copies enumerate copies or split into binary groups descending after binary splitting
grouped / multiple-choice knapsack at most one item per group choose none or one from current group descending

This table captures the most important algorithmic difference among the standard knapsack variants.


8. Complexity and Theory Notes⭐

8.1 Pseudo-Polynomial Nature

For 0-1 and unbounded knapsack, the standard capacity-indexed dynamic programs run in $O(NV)$ time. Bounded and grouped variants introduce additional factors associated with copy limits or group sizes.

However, dependence on the numerical capacity $V$ does not make these algorithms polynomial in the formal complexity-theoretic sense [3].

The reason is that the capacity $V$ is a numerical value, while the input length only needs

$$ O(\log V) $$

bits to encode it.

So an $O(NV)$ algorithm is generally pseudo-polynomial, not polynomial in the binary input length.

This complexity also explains why the integer / discretized capacity assumption matters computationally. If decimal data are scaled by a factor $q$, the effective capacity becomes approximately $qV$, and the running time grows accordingly.

This is exactly why 0-1 knapsack can be NP-hard even though it admits a practical DP algorithm.

8.2 Weak NP-Hardness

The ordinary 0-1 knapsack optimization problem is a classical example of a weakly NP-hard problem [3].

This means:

  • it is NP-hard in general;
  • but it admits a pseudo-polynomial dynamic program.

That is one of the main reasons the knapsack problem is used so often in algorithm courses and integer-programming courses.


9. Key Takeaways⭐⭐⭐

  1. The knapsack problem is a classical resource-allocation problem under a capacity constraint.
  2. The decision version is NP-complete, while the optimization version is NP-hard.
  3. The classical $O(NV)$ capacity-indexed DP assumes that weights and capacity are integer-valued or discretized to integers; the item values themselves do not need to be integers.
  4. The central DP task is to define a good state and derive the correct recurrence.
  5. For 0-1 knapsack, the 1D capacity loop must go from large to small.
  6. For complete knapsack, the 1D capacity loop must go from small to large.
  7. Bounded knapsack can be efficiently reduced to a 0-1 knapsack problem by binary splitting, which replaces a copy-count decision by a logarithmic number of 0-1 bundle decisions.
  8. Grouped / multiple-choice knapsack treats each group as one stage; a descending capacity loop prevents selecting more than one item from the same group in the 1D implementation.
  9. The usual DP algorithms for knapsack are typically pseudo-polynomial, not polynomial in the encoded input length.

References

  1. Sun, Xiaoling, and Duan Li. Integer Programming. Beijing: Science Press, 2010. ISBN: 978-7-03-029380-0.(孙小玲、李端:《整数规划》,北京:科学出版社,2010年,ISBN:978-7-03-029380-0)
  2. Martello, Silvano, and Paolo Toth. Knapsack Problems: Algorithms and Computer Implementations. Chichester: John Wiley & Sons, 1990. ISBN: 978-0-471-92420-3.
  3. Kellerer, Hans, Ulrich Pferschy, and David Pisinger. Knapsack Problems. Berlin: Springer, 2004. DOI: 10.1007/978-3-540-24777-7.
  4. Merkle, Ralph C., and Martin E. Hellman. “Hiding Information and Signatures in Trapdoor Knapsacks.” IEEE Transactions on Information Theory 24(5), 1978, 525–530. DOI: 10.1109/TIT.1978.1055927.
  5. Bellman, R. Dynamic Programming. Princeton University Press, 1957. ISBN: 978-0-691-07951-6.

Suggested Follow-up Reading

The most relevant next topics are:

  1. Assignment Problem
    A useful contrast to knapsack: it is also a structured combinatorial optimization problem, but unlike knapsack it admits polynomial-time algorithms.

  2. Approximation Algorithms
    Especially relevant for NP-hard problems such as knapsack, where exact polynomial-time algorithms may not exist but high-quality solutions with provable guarantees can still be obtained.

  3. Branch and Bound / Branch and Cut
    Useful for understanding how more general integer-programming methods solve knapsack-type models beyond pseudo-polynomial dynamic programming.

  4. Column Generation and Decomposition Methods
    Helpful for seeing how very different large-scale optimization techniques compare with dynamic programming on special structures.