Data Structures and Algorithms • C# examples
0/1 Knapsack and Subset-Sum Dynamic Programming
Optimize a bounded selection where each item may be chosen at most once.
Concept
In 0/1 knapsack, each item is either selected or skipped under a capacity limit. A common state is the best value using the first i items with capacity c. A one-dimensional optimization must iterate capacities downward so the current item is not reused accidentally.
How to approach it
Define whether the target is maximum value or reachability; choose loop direction according to whether reuse is allowed.
Complexity
O(nW) time and O(W) memory for n items and integer capacity W.
C# example
for (int item = 0; item < weights.Length; item++)
for (int capacity = limit; capacity >= weights[item]; capacity--)
dp[capacity] = Math.Max(
dp[capacity], dp[capacity - weights[item]] + values[item]);
Expected result or behavior
Descending capacity ensures each item contributes at most once in the 0/1 formulation.
Practice exercise
Change the loop direction for unbounded knapsack and explain the difference.
Key takeaway: A small change in iteration order can change the meaning of a DP transition.