Knapsack Problem

Context: FIT2004_MOC · “given a limitation (cost), optimise something (profit)” — the pass-level DP where the state question “is the weight alone enough?” decides between a 1-D array and a 2-D matrix Parent Framework: Dynamic Programming

Quick Revision

  • 🎯 Objective: capacity , items with weight and value ➔ maximise total value subject to total weight .
  • 📦 Core Components: unbounded (items unlimited) ➔ 1-D memo[weight], time, space | 0/1 / bounded (each item once) ➔ 2-D DP[item][weight], time and space.
  • ⚡ Key Constraint: the variant changes the state, not the recurrence’s spirit. Unlimited items ⟹ the item set never shrinks ⟹ weight alone is a sufficient state. Once each item is single-use, which items remain must be in the state, and that is the extra dimension.

📝 How It Works

1. Same Skeleton as Coin Change

  • The lecturer’s own framing ➔ “very similar to the coin change, except: finding maximum instead of minimum, and initialised to 0 instead of .”
  • Weight plays the role of value ➔ coin change sweeps target values ; knapsack sweeps capacities .
  • The item is the choice, not the subproblem ➔ items are tried inside each cell, exactly as coins were ➔ Dynamic Programming §5.
  • Initialise to , not ➔ taking nothing is always legal and worth , so there is no unreachable case here; a knapsack can always be left empty.
  • Running example (both variants) ➔ capacity kg.
Item
Weight kg kg kg kg
Value\230$\40$\350$\550$

2. Unbounded — One Dimension Is Enough

  • Why weight alone is a sufficient state ➔ items are unlimited, so after taking one the set of options is unchanged; nothing about the past constrains the future except the remaining capacity.
  • MEMO sentence ➔ memo[w] = {the maximum value obtainable with total weight at most w}.
  • The carry term is a correctness fix, not decoration ➔ without it the table means “maximum value at total weight exactly ”, and the answer breaks when the capacity cannot be filled exactly or the optimum sits below it (e.g. best at kg with a kg bag). The lecture gives two repairs: memo[w] = memo[w-1] or a linear search of the memo for its maximum.
  • Hand-filling rule ➔ at each weight, test every item: too heavy ⟹ skip; fits ⟹ “optimal of plus this item’s value”, keep the best.
  • Cost ➔ cells items time, auxiliary.

3. 0/1 (Bounded) — the Second Dimension Is the Item Set

  • Why the 1-D table now fails ➔ having taken item , the option set has changed; a 1-D memo[w] cannot tell you whether is still available, so it would happily take it twice.
  • The lecture’s framing ➔ “grow from weight to weight, and grow from a set of items to a set of items” — the rows are , , , , .
  • MEMO sentence ➔ DP[i][w] = {the maximum value using only the first i items, with total weight at most w}.
  • Two base cases, both rows of zeros ➔ no item to choose from and max weight is .
  • The exclude branch is the correction the lecture stops to make ➔ at the naive ” fits, so take it” gives , but the row above already holds from item ; “here we can choose not to include , having only in the bag” ⟹ the cell is .
  • Always read from the row ABOVE ➔ , never the current row. Reading the current row makes the item reusable and silently turns the 0/1 problem back into the unbounded one.
  • Cost ➔ time and space.

4. The Space-Saving Trick — and Why It Is Usually Unusable

  • The observation ➔ every cell reads only the row above, so only two rows are ever live: keep the previous row and the current one and discard the rest.
  • What it buys ➔ space falls from (the whole matrix) to two rows; time is unchanged.
  • What it costs ➔ reconstruction dies. Recovering the item set needs the whole matrix to compare each cell with the one above it, so “in reality we can’t do this space saving — because we need it to reconstruct the solution.”
  • The selection rule ➔ asked only for the value, roll the rows; asked “which items”, keep the matrix ➔ Dynamic Programming §7.
  • Generalises ➔ any DP whose recurrence looks back a bounded number of rows can be rolled, and every one of them loses its breadcrumbs ➔ Maximum Subarray Sum §2, Longest Common Subsequence (LCS) §Implementation.

5. Reconstruction — Compare Against the Row Above

  • The test ➔ at , compare with . Same value ⟹ item was excluded (move up one row); different ⟹ item was included (record it, move up one row and left by ).
  • Why the test is sound ➔ the cell is a of exactly those two branches, so a value that differs from the exclude branch can only have come from the include branch — this is inclusion–exclusion, no decision array required.
  • Stop ➔ when or .
  • This is what the lecture calls backtracking ➔ as opposed to a decision array, which stores the choice at write time; the array is faster, backtracking uses less auxiliary space at the same complexity ➔ Coin Change §5.

⚙️ Core Implementation

🔹 Unbounded knapsack

🔹 0/1 knapsack, with item reconstruction

⚖️ Complexity

items, capacity (the lecturer’s ).

VariantTimeAuxiliary spaceReconstruction
Unboundeddecision array , or backtrack
0/1, full matrix✅ compare against the row above
0/1, two rows only❌ impossible
Brute force (0/1) stackevery subset
  • All cases coincide ➔ the loops are input-independent, so best average worst for every DP row above.
  • is a numeric capacity, not an element count ➔ is pseudo-polynomial: doubling the capacity’s bit-length squares the work. State the unit-cost assumption ➔ Algorithmic Complexity §Input size.

📊 Exam Execution Trace & Applied Exercises

Manual Execution Trace — unbounded, capacity

Weight
Profit

Final Extracted Output: \mathbf{\780}2\times C + 2\times B5+1=12$700+$80$)*.

  • Read ➔ five copies of give ; item alone gives . The takes , and five s were never the answer — the cell is a running maximum.
  • Read ➔ beats and six s . The heaviest single item is rarely the answer.
  • Read ➔ alone beats ; but at , beats . The optimal item set changes non-monotonically with capacity — you cannot extend the answer greedily.

Manual Execution Trace — 0/1, capacity

Rows are the growing item set; every cell reads only the row above.

Items \ Weight

Backtracking pass (compare each cell with the one directly above)

AtCellRow aboveVerdictMove to
same ⟹ exclude
differs ⟹ include (5 kg)
differs ⟹ include (1 kg)
differs ⟹ include (6 kg) ➔ stop

Final Extracted Output: — kg for \230+$40+$350=\mathbf{$620}$, matching the lecture.

  • Read the trap at ➔ fits and offers , but excluding inherits from item . The cell is ; a student who only ever adds the fitting item writes and corrupts every cell to its right.
  • Read the variant difference ➔ the unbounded answer is \780$620$ on the same items and capacity. Quoting one for the other is a whole-question error.
  • Read row ➔ *( kg, \550w=9,10,11w=12{A,B,C}$ fills the bag exactly for more.

Applied Exercise — why unbounded needs one dimension and 0/1 needs two

Final Extracted Output: the row index encodes “only the first items are on offer”, and processing items in a fixed order is what makes one index enough instead of a subset. The reusable move (LO1): ask “does my subproblem parameter determine the future?” — the same question that adds a dimension in Dynamic Programming §5 and widens a vertex in State-Space Graph Modelling.

⚠️ Common Mistakes

  • 💡 Reading the current row in the 0/1 recurrence ➔ silently solves the unbounded problem; the fix is one index, DP[i-1][...].
  • 💡 Omitting the exclude branch ➔ “the item fits, so take it” discards a better set already found with fewer items; the cell is a of two branches.
  • 💡 Forgetting the unbounded carry ➔ the table silently means exactly , so an unfillable capacity returns garbage; carry memo[w-1] or scan for the max.
  • 💡 Applying the space-saving trick when the items are wanted ➔ two rows compute the value and destroy the reconstruction ➔ §4.
  • 💡 Calling polynomial ➔ is a numeric capacity, so this is pseudo-polynomial; say so when the capacity is given as a number.
  • 💡 Greedy by value-per-kilogram ➔ correct for the fractional problem only, which this unit does not ask for; on at kg it is not guaranteed ➔ Greedy Algorithm §5.

🧠 Active Recall