Abstract flowing gradient in deep indigo and blue tones, smooth and luminous, evoking a modern digital learning atmosphere

Computer Science and programming articles. We do not sell courses.

Knapsack dynamic programming for 0/1 and unbounded items

Dynamic programming turns a large collection of possible choices into smaller, reusable states. This guide explains how to solve the knapsack problem with dynamic programming, covering both the 0/1 and unbounded versions. In each version, items have a weight and a value, a capacity limits the total weight, and the goal is to maximise the total value.

The names describe how often an item may be selected. A 0/1 item can be packed once, like a camera in a travel bag. An unbounded item may be selected repeatedly, like multiple identical boxes of tea in a delivery carton. The same core idea—recording the best result for every capacity—serves both variants, but their updates differ in one important way.

A brute-force search examines every subset and quickly becomes impractical. Dynamic programming instead reuses answers to subproblems. Its running time is usually written as O(nW), where n is the number of items and W is the capacity, so it is pseudo-polynomial rather than polynomial in the number of combinations. A one-dimensional table can also reduce memory usage from O(nW) to O(W).

An Australian example might be packing a weekend kit: a camera, a laptop, books and groceries bought during a specials run through Woolworths or Coles. Metric kilograms and litres make the capacities easy to read. If the same kit is being assembled for an arvo in the park—“arvo” meaning afternoon—the programming model is unchanged; only the values attached to the gear change.

Recognising the two variants

Let item i have weight w[i] and value v[i]. The input also contains a non-negative capacity W, and the objective is to find a selection whose combined weight is no greater than W while its combined value is as large as possible. The bounded version is commonly called 0/1 knapsack because each item has two states: packed or left behind.

The unbounded version is also called complete knapsack. It asks how many copies of each item should be packed, with each copy contributing both weight and value. For example, packing a Bunnings DIY kit might include several identical boxes of screws. A bounded model permits one box, while an unbounded model permits as many as the remaining capacity allows.

Greedy selection by value-to-weight ratio does not guarantee an optimum. Consider items with weights and values (6, 12), (5, 8) and (5, 9) for a capacity of 10. Choosing the first item because of its ratio leaves too little room for either remaining item, producing a value of 12. The better selection is the last two items, with a combined weight of 10 and value of 17. Dynamic programming avoids this trap by considering both taking and skipping each item.

Deriving the 0/1 recurrence

Define D[i][c] as the maximum value obtainable using the first i items with capacity c. For every item, the algorithm compares two possibilities: leave it out and retain D[i-1][c], or take it and add its value to D[i-1][c-w[i]]. Thus, when the item fits:

D[i][c] = max(D[i-1][c], v[i] + D[i-1][c-w[i]])

When it does not fit, D[i][c] remains equal to D[i-1][c]. The base case is D[0][c] = 0, since no value can be obtained without items. Filling the table from smaller item counts to larger ones ensures every required smaller subproblem has already been calculated.

For example, suppose the weights are [2, 3, 4], the values are [20, 40, 50] and the capacity is 5. The items weighing 2 and 3 can be combined for a total weight of 5 and a value of 60, which is better than taking the 4-kilogram item by itself.

A direct Python implementation mirrors the recurrence:

def zero_one_knapsack(weights, values, capacity):
    n = len(weights)
    dp = [[0] * (capacity + 1) for _ in range(n + 1)]

    for i in range(1, n + 1):
        for c in range(capacity + 1):
            dp[i][c] = dp[i - 1][c]
            if weights[i - 1] <= c:
                dp[i][c] = max(
                    dp[i][c],
                    values[i - 1]
                    + dp[i - 1][c - weights[i - 1]]
                )

    return dp[n][capacity]

This table takes O(nW) time and O(nW) memory. If only the optimal value is required, the same recurrence can be stored in one array. Items must then be processed in descending capacity order; otherwise, the current item could be reused within the same pass and the solution would no longer be strictly 0/1.

Allowing unlimited copies

The unbounded variant changes the state used by the “take” option. With U[i][c] representing the best value from the first i item types, taking another copy of item i refers to U[i][c-w[i]] rather than the previous row. The current row can therefore contain the item again, allowing repeated copies until the capacity is exhausted.

This recurrence can be implemented with one-dimensional storage and an ascending capacity loop:

def unbounded_knapsack(items, capacity):
    dp = [0] * (capacity + 1)

    for weight, value in items:
        if weight <= 0:
            raise ValueError("Item weights must be positive")

        for c in range(weight, capacity + 1):
            dp[c] = max(dp[c], dp[c - weight] + value)

    return dp[capacity]

The ascending loop is significant. When dp[c-weight] is read, it may already include a copy of the current item, so another copy can be added. A descending loop would produce the bounded behaviour instead. Both implementations use O(nW) time, while this unbounded version needs only O(W) memory.

For comparison, a 2-kilogram item valued at 30 and a capacity of 4 produce a value of 30 in the 0/1 version but 60 in the unbounded version. The zero-initialised array also defines an “at most this capacity” problem, where leaving space unused is permitted. If the weight must exactly equal the capacity, unreachable states need a different initial value.

Recovering selections and avoiding errors

A two-dimensional table supports more than the final optimum. Start at D[n][W] and compare it with D[n-1][W]. If they differ, the last item was included; record it and reduce the remaining capacity by its weight. If they are equal, the item can be skipped. Continuing backward produces one valid optimal selection. Ties may allow several selections, but the procedure returns one of them without affecting the optimal value.

Several implementation mistakes are easy to miss. Zero-weight items can cause an unbounded update to depend on the same state indefinitely, while negative weights make “unlimited” copies meaningless. Capacity must also be an integer when arrays index the states directly. Floating-point values can be handled by the algorithm, although rounding becomes another source of error. It is worth testing whether item order changes the answer; it should not.

Related combinatorial problems also depend on carefully checking whether a locally attractive choice blocks a better complete result. For route selection, the Fleury algorithm guide illustrates this form of greedy decision-making and validity checking.

Real constraints can make the abstract model more intuitive. A traveller can use a Qantas economy carry-on allowance of 7 kilograms for many fares as the capacity, then decide whether a camera, laptop or book earns its place. The same weight limit applies in every recurrence, regardless of whether the destination is domestic or international.

A practical implementation and testing checklist

Before calculating a result, validate the input and define the semantics precisely. The implementation should distinguish a maximum value from the items that produce it, and it should document whether unused capacity and zero-valued items are allowed.

Testing should cover boundaries and both variants. The open hello ML community is a useful place to compare implementation details and edge cases with other learners.