TCS · Question 4 · Dynamic Programming
0/1 Knapsack Problem
Problem
Max value with a weight limit.
Approach
1D DP iterating capacity backward per item.
Time O(n*W)Space O(W)
How it works
- 1dp[w] = best value within capacity w.
- 2Backward iteration keeps items 0/1.
Sample input / output
Input: weights = [1, 3, 4, 5], values = [1, 4, 5, 7], W = 7 Output: 9
Constraints
1 <= n <= 100; 1 <= W <= 10^4.
Solution — read it, then walk it
Time O(n*W)Space O(W)Loops 2Returns 2source · C++
Scroll sideways for wide charts — the view follows the active step.
- start / end
- statement
- condition
- loop
- returns
- definition
1/16
StartSTART
Interactive control-flow diagram and step-by-step code walkthrough.
Recommended resourcesAffiliate links · may earn us a commission
Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits