cs-119 — The Knapsack Twins
| Field | Value |
|---|---|
| id | cs-119 |
| difficulty | Intermediate |
| topics | optimization, formulations |
| lecture | lecture-30 |
| estimated time | 5-minute attempt + 10-minute discussion |
| prerequisites | loops, lists, and tracing from lectures 1-6 |
| objective | choose the technique, trace it faithfully, and defend the boundary behaviour |
| solution | held by the instructor; discussed after the attempt |
Problem
Two university-trip packing variants (must-fill weight vs must-stay-under) change the algorithm. Same story, different formulation; recognise which is which.
Your deliverable is the enumerated answer, the space count, and the pruning rule with its measured effect. If the problem is ambiguous anywhere, state the assumption you are making and carry on — a stated assumption is part of a good answer.
Examples
- Input: items weight/value: (5, 30), (4, 26), (3, 14); capacity 8
- Output: 0/1 knapsack: best value 56 {(5,30)+(3,14)=44 no -> (4,26)+(3,14)=40? enumerate: (5,30)+(4,26) over; best = 30+14=44 or 26+14=40 -> 44; fractional would take 4/5 of first
Solve for the worked instance first. Then ask what would change if one number, name, or condition were replaced by something stranger.
What to notice
- 0/1 vs fractional knapsack are DIFFERENT problems with different algorithms - DP vs greedy-by-ratio.
- Brute force is a legitimate algorithm when the space is honest about its size.
- Pruning is not cheating; it is arithmetic applied early.
Discussion starter
After the solution is revealed, the class spends five minutes on this prompt: "Which constraint is cheapest to check first, and why does order matter?"
Constraints and assumptions
- Difficulty: Intermediate (loops and lists assumed).
- Topics: optimization, formulations.
- Classroom-scale inputs unless the problem says otherwise.
- Time-box: about five minutes for the plan and trace; finishing the details is a bonus, defending the method is the target.
- Optional stretch (not required): describe an alternative approach and say when it beats the obvious one.
Hints and extension
- First nudge: identify the pattern the worked instance uses before computing anything.
- If stuck after three minutes, write the input/output line you expect and trace the smallest example by hand.
- After the reveal, attempt the extension below before the next lecture.
- Extension challenge: Reformulate with a different objective and describe how the optimum moves.