Video in progress

Strong Middle 🧠 Problem solving

Solve the 0/1 knapsack problem and explain why the loop has to run backwards when you shrink the DP table to one dimension.

dp[w] is the largest value achievable with capacity w. For each item, dp[w] = max(dp[w], dp[w - weight] + value). I go over the capacity from large w to small, otherwise one item may get taken several times. O(n·W).

📖 Answer

static int knapsack(int[] weight, int[] value, int capacity) {
    int[] dp = new int[capacity + 1];
    for (int i = 0; i < weight.length; i++) {
        for (int w = capacity; w >= weight[i]; w--) {   // backwards!
            dp[w] = Math.max(dp[w], dp[w - weight[i]] + value[i]);
        }
    }
    return dp[capacity];
}

The reason for going backwards. In the 2D version, dp[i][w] looks only at the previous row dp[i-1][...]. In a one-dimensional array, dp[w - weight[i]] must still be not updated, meaning it must reflect the state from the earlier items. If you go from large w, the smaller indexes are still old. If you go from small, dp[w - weight] has already been updated with this item, and the item gets added a second time.

The interesting part: that same "mistake" is exactly the correct solution for unbounded knapsack (unlimited copies of each item). One loop direction changes the problem.

You should be honest about complexity: O(n·W) is pseudo-polynomial. If W = 10⁹, the table doesn't fit. Then you think about DP over value, meet-in-the-middle, or an approximate solution.

Real examples: the most profitable ad campaigns within a budget, or a set of tasks that fits within a server's resources.