Lesson 7 · Dynamic programming

Unbounded Knapsack

The knapsack problem where every item can be taken as many times as you like. The table shrinks to one row indexed by capacity, and the only change from the 0/1 version is the direction of one loop.

Unbounded Knapsack concept diagramTwo copies of a dp row for capacities 0 to 5 while adding item A (weight 1, value 6). Top: capacity swept from 5 down to 1; every cell reads an untouched 0 on its left and becomes 6, so A is used once. Bottom: capacity swept from 1 up to 5; every cell reads the value just written on its left, giving 6, 12, 18, 24, 30, so A is used up to five times.0/1 knapsack: capacity 5 → 1each cell reads a value this pass has not touched yet0c = 06c = 1 · 5th6c = 2 · 4th6c = 3 · 3rd6c = 4 · 2nd6c = 5 · 1st0 + 60 + 60 + 60 + 60 + 6dpUnbounded knapsack: capacity 1 → 5each cell reads the value this pass just wrote, so A stacks up0c = 06c = 1 · 1st12c = 2 · 2nd18c = 3 · 3rd24c = 4 · 4th30c = 5 · 5th0 + 66 + 612 + 618 + 624 + 6dpsame line dp[c] = max(dp[c], dp[c − 1] + 6) · only the loop direction differs
1

Unlimited Copies of Each Item

The unbounded knapsack gives you item types instead of single items. Each type has a weight and a value, and you may put in as many copies as fit. The goal is still the largest total value with total weight at most W.

This page reuses the items from the 0/1 knapsack lesson: A weighs 1 and is worth 6, B weighs 2 and is worth 10, C weighs 3 and is worth 12, and the capacity is 5. With one copy each, the best is B + C = 22. With unlimited copies, five A's give 30.

  • Real cases: cutting stock from standard lengths, making change from coin types, filling a budget with repeatable purchases
  • Because copies are free, the item index drops out of the state; capacity alone is enough
2

The Unbounded Knapsack Recurrence Relation

  1. Make an array dp of size W + 1, all zeros
  2. For each item, loop c from its weight up to W
  3. Set dp[c] = max(dp[c], dp[c − w] + v)
  4. The answer is dp[W]

Let dp[c] be the best value that fits in capacity c. Look at the last copy placed in the bag. It is some item i with wᵢ ≤ c, and what remains is a bag of capacity c − wᵢ that should itself be filled as well as possible. So dp[c] = max over all items i with wᵢ ≤ c of dp[c − wᵢ] + vᵢ, and dp[0] = 0. If no item fits, dp[c] = 0.

That is the unbounded knapsack recurrence relation. Compared with 0/1, the take case reads dp[c − wᵢ] for the same set of items, not the set without item i, which is exactly what lets the item appear again. It is the same shape as the rod cutting recurrence, where piece lengths are the weights and prices are the values.

  • Loop order between items and capacities does not matter for the maximum; capacity outer and items inner also works
  • To recover the items, store which item last improved each dp[c] and walk back from W
3

0/1 vs Unbounded Knapsack

In one-row form the two problems run the same line of code: dp[c] = max(dp[c], dp[c − w] + v). The difference between 0/1 and unbounded knapsack is only the direction of the capacity loop. Going upward, dp[c − w] has already been updated for this item, so the item can be added on top of itself. Going downward, dp[c − w] still holds the value from before this item, so it is used at most once.

The diagram above shows item A's pass both ways. Downward, every cell reads an old 0 and gets one copy: 6, 6, 6, 6, 6. Upward, each cell reads the cell its own pass just wrote: 6, 12, 18, 24, 30.

Same items, capacity 5
0/1 knapsackUnbounded knapsack
Copies of each itemAt most oneAny number
One-row capacity loopW down to ww up to W
Full-table take case readsRow i − 1Row i (same row)
Best value here22 (B + C)30 (5 × A)
  • Bounded knapsack (at most k copies) sits in between: split each item into copies of 1, 2, 4, ... and run the 0/1 loop
  • Swapping the loop direction by mistake gives a plausible but wrong number, so test on a case where they differ
Key reference

Terms, operations, and practical uses

Key terms

  • Item typeA weight and a value that can be taken any number of times.
  • dp[c]The best value that fits in capacity c, using any number of copies.
  • Bounded knapsackEach item has a limit k on copies; reduces to 0/1 by binary splitting.
Implementation

Code in Python, C++ and Java

WEIGHTS = [1, 2, 3]
VALUES = [6, 10, 12]
CAPACITY = 5


def unbounded(weights, values, capacity, forward=True):
    dp = [0] * (capacity + 1)
    last = [-1] * (capacity + 1)
    for i, (w, v) in enumerate(zip(weights, values)):
        order = range(w, capacity + 1) if forward else range(capacity, w - 1, -1)
        for c in order:
            if dp[c - w] + v > dp[c]:
                dp[c] = dp[c - w] + v
                last[c] = i
    return dp, last


def copies(last, weights, capacity):
    count = [0] * len(weights)
    c = capacity
    while c > 0 and last[c] != -1:
        count[last[c]] += 1
        c -= weights[last[c]]
    return count


def greedy_by_ratio(weights, values, capacity):
    total = 0
    for w, v in sorted(zip(weights, values), key=lambda p: p[1] / p[0], reverse=True):
        total += (capacity // w) * v
        capacity %= w
    return total


dp, last = unbounded(WEIGHTS, VALUES, CAPACITY)
print("dp by capacity 0 to", CAPACITY, ":", " ".join(map(str, dp)))
print("best value:", dp[CAPACITY])
print("copies used:", ", ".join(f"{k} x w{w} v{v}" for k, w, v in zip(copies(last, WEIGHTS, CAPACITY), WEIGHTS, VALUES) if k))
print("capacity backward (0/1 answer):", unbounded(WEIGHTS, VALUES, CAPACITY, False)[0][CAPACITY])

w2, v2, cap2 = WEIGHTS[1:], VALUES[1:], 7
dp2, last2 = unbounded(w2, v2, cap2)
print("without w1, capacity 7: dp", dp2[cap2], "greedy by ratio", greedy_by_ratio(w2, v2, cap2))
print("copies used:", ", ".join(f"{k} x w{w} v{v}" for k, w, v in zip(copies(last2, w2, cap2), w2, v2) if k))
print("without w1, capacity 1:", unbounded(w2, v2, 1)[0][1])
#include <algorithm>
#include <cstdio>
#include <numeric>
#include <string>
#include <vector>
using namespace std;

struct Result { vector<int> dp, last; };

Result unbounded(const vector<int>& w, const vector<int>& v, int capacity, bool forward = true) {
    Result r{vector<int>(capacity + 1, 0), vector<int>(capacity + 1, -1)};
    for (size_t i = 0; i < w.size(); i++) {
        auto relax = [&](int c) {
            if (r.dp[c - w[i]] + v[i] > r.dp[c]) { r.dp[c] = r.dp[c - w[i]] + v[i]; r.last[c] = i; }
        };
        if (forward) for (int c = w[i]; c <= capacity; c++) relax(c);
        else for (int c = capacity; c >= w[i]; c--) relax(c);
    }
    return r;
}

string copies(const Result& r, const vector<int>& w, const vector<int>& v, int capacity) {
    vector<int> count(w.size(), 0);
    for (int c = capacity; c > 0 && r.last[c] != -1; c -= w[r.last[c]]) count[r.last[c]]++;
    string s;
    for (size_t i = 0; i < w.size(); i++)
        if (count[i]) s += (s.empty() ? "" : ", ") + to_string(count[i]) + " x w" + to_string(w[i]) + " v" + to_string(v[i]);
    return s;
}

int greedyByRatio(const vector<int>& w, const vector<int>& v, int capacity) {
    vector<int> idx(w.size());
    iota(idx.begin(), idx.end(), 0);
    sort(idx.begin(), idx.end(), [&](int a, int b) { return v[a] * w[b] > v[b] * w[a]; });
    int total = 0;
    for (int i : idx) { total += (capacity / w[i]) * v[i]; capacity %= w[i]; }
    return total;
}

int main() {
    vector<int> W = {1, 2, 3}, V = {6, 10, 12};
    int cap = 5;
    Result r = unbounded(W, V, cap);
    printf("dp by capacity 0 to %d :", cap);
    for (int x : r.dp) printf(" %d", x);
    printf("\nbest value: %d\n", r.dp[cap]);
    printf("copies used: %s\n", copies(r, W, V, cap).c_str());
    printf("capacity backward (0/1 answer): %d\n", unbounded(W, V, cap, false).dp[cap]);

    vector<int> W2 = {2, 3}, V2 = {10, 12};
    Result r2 = unbounded(W2, V2, 7);
    printf("without w1, capacity 7: dp %d greedy by ratio %d\n", r2.dp[7], greedyByRatio(W2, V2, 7));
    printf("copies used: %s\n", copies(r2, W2, V2, 7).c_str());
    printf("without w1, capacity 1: %d\n", unbounded(W2, V2, 1).dp[1]);
}
import java.util.ArrayList;
import java.util.List;

public class Main {
    static int[][] unbounded(int[] w, int[] v, int capacity, boolean forward) {
        int[] dp = new int[capacity + 1], last = new int[capacity + 1];
        java.util.Arrays.fill(last, -1);
        for (int i = 0; i < w.length; i++) {
            for (int k = 0; k <= capacity - w[i]; k++) {
                int c = forward ? w[i] + k : capacity - k;
                if (dp[c - w[i]] + v[i] > dp[c]) { dp[c] = dp[c - w[i]] + v[i]; last[c] = i; }
            }
        }
        return new int[][] {dp, last};
    }

    static String copies(int[] last, int[] w, int[] v, int capacity) {
        int[] count = new int[w.length];
        for (int c = capacity; c > 0 && last[c] != -1; c -= w[last[c]]) count[last[c]]++;
        List<String> parts = new ArrayList<>();
        for (int i = 0; i < w.length; i++)
            if (count[i] > 0) parts.add(count[i] + " x w" + w[i] + " v" + v[i]);
        return String.join(", ", parts);
    }

    static int greedyByRatio(int[] w, int[] v, int capacity) {
        Integer[] idx = new Integer[w.length];
        for (int i = 0; i < w.length; i++) idx[i] = i;
        java.util.Arrays.sort(idx, (a, b) -> Integer.compare(v[b] * w[a], v[a] * w[b]));
        int total = 0;
        for (int i : idx) { total += (capacity / w[i]) * v[i]; capacity %= w[i]; }
        return total;
    }

    public static void main(String[] args) {
        int[] W = {1, 2, 3}, V = {6, 10, 12};
        int cap = 5;
        int[][] r = unbounded(W, V, cap, true);
        StringBuilder s = new StringBuilder("dp by capacity 0 to " + cap + " :");
        for (int x : r[0]) s.append(" ").append(x);
        System.out.println(s);
        System.out.println("best value: " + r[0][cap]);
        System.out.println("copies used: " + copies(r[1], W, V, cap));
        System.out.println("capacity backward (0/1 answer): " + unbounded(W, V, cap, false)[0][cap]);

        int[] W2 = {2, 3}, V2 = {10, 12};
        int[][] r2 = unbounded(W2, V2, 7, true);
        System.out.println("without w1, capacity 7: dp " + r2[0][7] + " greedy by ratio " + greedyByRatio(W2, V2, 7));
        System.out.println("copies used: " + copies(r2[1], W2, V2, 7));
        System.out.println("without w1, capacity 1: " + unbounded(W2, V2, 1, true)[0][1]);
    }
}
Watch it run

Step through it

Running on A (weight 1, value 6), B (2, 10), C (3, 12), capacity 5; then without A, capacity 7

items, unlimited copies of eachA · w1 · v6B · w2 · v10C · w3 · v12000102030405dpcapdp[c] = max(dp[c], dp[c − w] + v), c from w up to 5Same items and capacity as the 0/1 knapsack lesson (answer there: 22).
Step 1

Start: zeros, sweep upward

dp[c] is the best value in capacity c. The loop is the 0/1 loop with one change: capacity runs from the item's weight up to 5, not down. That order is the whole difference between the two problems.

Output
1 / 12
4

Complexity and When Greedy Fails

There are W + 1 capacities and each looks at n items, so the time is O(n·W) and the space is O(W). Like 0/1 knapsack, this is pseudo-polynomial: fast when W is small, not when W has many digits.

With unlimited copies it is tempting to fill the bag with the best value-per-weight item. On the main set that happens to work, because A has the best ratio and weight 1 divides every capacity. Remove A and use capacity 7: B is worth 5 per unit, C 4 per unit. Greedy takes three B's (weight 6, value 30) and wastes the last unit. The table finds two B's and one C, weight 7, value 32.

  • Greedy is only safe when the best-ratio item's weight divides the capacity, or items can be cut
  • If the bag must be filled exactly, start every dp cell at −∞ except dp[0] = 0; a cell still at −∞ cannot be filled exactly
5

Problems That Are Unbounded Knapsack

Many interview problems are this recurrence with a different operation in place of max. Coin change asks for the fewest coins, so max becomes min and the value of each coin is 1. Coin change II counts the ways, so max becomes +, and there the loop order does matter: items outer counts combinations, capacity outer counts ordered sequences.