← capítulo

Dynamic programming: the knapsack family

Maximize value in a limited bag. One rule — fractions allowed? — decides greedy vs DP.

Fractional vs 0/1

The 0/1 DP: take or skip

Watch the table fill

Green = item taken here · grey = skipped. dp[4][7] = 9 (items 3+4). Density-greedy grabs the 5-weight item first → only 8.

Greedy has no guarantee

Greedy ~95% average but WORST case → 0 (item A=(1,2), B=(W,W), bag W: greedy 2, optimum W). Fractional 136% = a loose upper bound (relaxation gap).

Pseudo-polynomial

Takeaway

Fractions allowed → greedy. All-or-nothing → DP. That's the whole difference. DP makes the state space explicit — but a huge state space still bites. Next: edit distance & LCS — DP on sequences (diff, spell-check, DNA).