Algorithm Atlas · worked example
See the algorithm, step by step
Update capacities backward so each item contributes at most once.
This call is starting. Local values appear as they are initialized.
Data & variables
Changed Source indexExample input
weights=[1,3,4,5] values=[1,4,5,7]Follow the code. Data appears here when it enters scope.
Call stack · 1 frame
maincall 1
Rust source
Line 13fn knapsack(weights: &[usize], values: &[i32], capacity: usize) -> i32 {
assert_eq!(weights.len(), values.len());
let mut dp = vec![0; capacity + 1];
for (&weight, &value) in weights.iter().zip(values) {
for c in (weight..=capacity).rev() {
dp[c] = dp[c].max(dp[c - weight] + value);
}
}
dp[capacity]
}
fn main() {
let result = knapsack(&[1, 3, 4, 5], &[1, 4, 5, 7], 7).to_string();
println!("{result}");
}
Try your own version
Compare the visible input `weights=[1,3,4,5] values=[1,4,5,7]` with `weights=[8] values=[99]`. Predict why their results are `9` and `0`. Then change one legal value and explain whether the same invariant, the item must not be reused through a state updated in the same pass, still applies.
Open personal copy in Playground ↗Start with this exact source and input, change a value, then use Run or Debug locally. This replay stays attached to the original example.
Recordings use a native Rust target. Playground runs on wasm32-wasip1; target-sized types such as usize can have different limits.

Understand it
With capacity 7, weights [1,3,4,5] and values [1,4,5,7], combining weights 3 and 4 gives value 9. An ascending capacity loop could repeatedly reuse the same item and silently solve a different, unbounded problem.
The worked program is a complete executable for this pattern. Its core function uses typed input so the state transitions remain visible. The challenge input contract is: Return maximum value at capacity 7. The visible fixture is weights=[1,3,4,5] values=[1,4,5,7] and its example result is 9. The implementation and additional semantic fixtures were checked against an independent reference calculation. Those bounded tests establish these examples; they are not a proof for all inputs or a measurement on an iPhone.
Return a canonical String from solve: lowercase true/false for booleans; decimal integers without extra signs, leading zeros or whitespace; comma-separated sequence values and semicolon-separated groups. Whole-number medians have no decimal suffix; half medians use .5. Do not append a newline to the returned value. Preserve the explicitly named textual sentinels such as none or #. Input fixtures are bounded so the demonstrated arithmetic fits its named Rust types; satisfy the stated input preconditions before applying the algorithm.
String and character-grid fixtures use ASCII unless the lesson explicitly specifies Unicode scalar values.
A problem is a good match for 0/1 Knapsack when it asks for bounded selection under one capacity. Here the concrete task is: Return maximum value at capacity 7. The visible input weights=[1,3,4,5] values=[1,4,5,7] is an example, not a definition of the whole problem. Ask what operations the solution must support and what the input guarantees. Choose a recurrence when subproblems overlap. Some patterns summarize a frontier instead of a full DP table; either representation needs an invariant, and any greedy shortcut needs proof. The right choice follows from those guarantees, not from a familiar noun in the prompt.
The decisive invariant is: Update capacities backward so each item contributes at most once. Try to say why it applies to the task without quoting the implementation. Which fact becomes known after one update, and which possible answers remain? A one-dimensional DP state summarizes a prefix or a single parameter. Define its meaning before writing a recurrence. If that claim cannot be maintained on a legal input, the pattern is wrong or one of its preconditions is missing. A counterexample is more useful than a vague warning: change one property of the sample, trace the first two steps, and identify the exact claim that fails.
Compare costs before committing. The advertised bound is O(items*capacity) time · O(capacity) space; identify the operation responsible for it and the extra memory it needs. Then compare a straightforward alternative: a direct scan, full sort, or repeated recomputation may be easier but can pay for the same work many times. Do not choose the more elaborate method just because it has a famous name. For the sample, predict 9 and explain which part of the state lets the method reach that result.
When the prompt is ambiguous, ask about input size, ordering, duplicates, and required output format. Test the base state, the first transition, impossible states, and whether an in-place update accidentally reuses an item twice. Use Option or a safe sentinel for unreachable states, and choose an iteration direction that matches the recurrence's dependencies. The Rust sketch can show a useful primitive without proving that the whole task is solved; connect each primitive to the requested output. You should be able to name a fitting case, a near miss, and the assumption separating them before writing the first line.
The pattern
Update capacities backward so each item contributes at most once.
When to use it: bounded selection under one capacity
Complexity: O(items*capacity) time · O(capacity) space
Input: weights=[1,3,4,5] values=[1,4,5,7]
Read the code
fn knapsack(weights: &[usize], values: &[i32], capacity: usize) -> i32 {
assert_eq!(weights.len(), values.len());
let mut dp = vec![0; capacity + 1];
for (&weight, &value) in weights.iter().zip(values) {
for c in (weight..=capacity).rev() {
dp[c] = dp[c].max(dp[c - weight] + value);
}
}
dp[capacity]
}
fn main() {
let result = knapsack(&[1, 3, 4, 5], &[1, 4, 5, 7], 7).to_string();
println!("{result}");
}
Complete std-only zero-one-knapsack program for its typed teaching fixture. Parsing and output construction are separate from the core algorithm.
Try it
Compare the visible and independent fixtures. Explain the input assumption that makes this algorithm applicable, then identify a change that would invalidate it.
What success looks like: You can justify the choice from constraints rather than from a remembered problem title.
Check your understanding
Trace 0/1 Knapsack on input weights=[2,2,3] values=[3,4,5]. Which result follows from the documented contract?
Reveal the answer
131211
For this input the result is 12. The item must not be reused through a state updated in the same pass. Compare this independent fixture with the worked trace: With capacity 7, weights [1,3,4,5] and values [1,4,5,7], combining weights 3 and 4 gives value 9. An ascending capacity loop could repeatedly reuse the same item and silently solve a different, unbounded problem.
Go deeper
Common misconception: “Downward iteration makes items unlimited”
The item must not be reused through a state updated in the same pass. With capacity 7, weights [1,3,4,5] and values [1,4,5,7], combining weights 3 and 4 gives value 9. An ascending capacity loop could repeatedly reuse the same item and silently solve a different, unbounded problem.
- Concrete transition: With capacity 7, weights [1,3,4,5] and values [1,4,5,7], combining weights 3 and 4 gives value 9. An ascending capacity loop could repeatedly reuse the same item and silently solve a different, unbounded problem.
- Independent second fixture: Input
weights=[2,2,3] values=[3,4,5]produces12. Execute the named function in the worked program with these typed arguments, then compare its actual result with this independently computed expectation. - Boundary and contract: Input
weights=[1,6] values=[2,8]produces10. The item must not be reused through a state updated in the same pass. The stated work bound is O(items*capacity) time · O(capacity) space. Count actual state changes; a successful output test alone does not prove that bound.
Transfer challenge: Compare the visible input weights=[1,3,4,5] values=[1,4,5,7] with weights=[8] values=[99]. Predict why their results are 9 and 0. Then change one legal value and explain whether the same invariant, the item must not be reused through a state updated in the same pass, still applies.
Connections
- 0/1 Knapsack: Mental Model: Update capacities backward so each item contributes at most once.
- Challenge: 0/1 Knapsack: Return maximum value at capacity 7.
Reveal the Algorithm Atlas answer
9
Learn this lesson with AI
Paste this into Claude, Codex, Cursor or another agent connected to Crabrix Academy. It contains only this lesson’s public details.
I'm learning Rust with Crabrix Academy. Teach me this lesson with the Crabrix Academy tools. Lesson: 0/1 Knapsack: When to Use It (courseId "algorithms", lessonId "algorithm.zero-one-knapsack.recognize") Link: https://crabrix.com/learn/algorithms/algorithm.zero-one-knapsack.recognize Goal: The item must not be reused through a state updated in the same pass. State the input preconditions before applying this invariant. Practice: open the starter in the Crabrix Playground (https://crabrix.com/playground/?lesson=algorithms/algorithm.zero-one-knapsack.recognize) and I will write the code there. Explain it step by step for my level, let me write the code myself, give hints before any solution, and do not mark anything as passed: only Crabrix checks do that.