0/1 knapsack DP — the OilKnapsack bridge
◈ 6 cardsThe dp[i][w] knapsack recurrence with reconstruction, pseudo-polynomial cost, and the same shape applied to the OilKnapsack project.
The 0/1 knapsack problem
items; item has weight and value . A knapsack holds capacity . Each item is taken whole or not at all (the 0/1 constraint). Maximize total value without exceeding .
Greedy by value-density fails here (you will see exactly why in Module 5) — a whole item you skip can leave wasted capacity. The fix is DP.
Optimal substructure & recurrence
Let be the best value using only the first items within capacity . For item you either skip it or take it: with base case . Fill the table row by row.
Worked example: the CLRS counterexample
Items : $(10,\$60),(20,\$100),(30,\$120)W=50$. Greedy-by-density takes item 1 then item 2 for \$160; the DP finds items 2 + 3 = \$220. The table below prints the optimal value and reconstructs the chosen item indices.
Reconstruction
From , walk up: if , item was taken — record it and drop by . Otherwise it was skipped. This is the same stored-choice idea as rod cutting and LCS.
Pseudo-polynomial cost — the trap
The table is . That is not polynomial in the input size: takes only bits to write down, so is exponential in the bit-length of . We call this pseudo-polynomial. (0/1 knapsack is NP-complete; no truly polynomial algorithm is known.)
The OilKnapsack project — same shape, one twist
The AU final project, OilKnapsack, is this DP in disguise. The company will produce barrels. Order wants barrels for total price (which may be negative); each order is filled wholly or not at all. The company need not sell everything, but pays storage per unsold barrel. Maximize profit (which may be negative).
Map it: orders = items, barrels = weight, capacity = . The twist is the objective. Track = the best revenue selling exactly barrels using the first orders (or if is unreachable). Then which charges storage on the unsold barrels and lets you stop short of selling all the oil. Because prices can be negative, the DP naturally skips unprofitable orders. The project rubric demands the full method: subproblems, recurrence, an acyclicity argument (each cell depends only on row , so the dependency graph is a DAG), base cases, reconstruction, and an running-time analysis — exactly the pieces below.
The second exercise runs the OilKnapsack DP on a small instance with a negative-price order, printing the max profit and which orders to fill.