← TCS bank

TCS · Question 4 · Dynamic Programming

0/1 Knapsack Problem

Dynamic ProgrammingC++code⏱ O(n*W)💾 O(W)
Service-based

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

  1. 1dp[w] = best value within capacity w.
  2. 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.
↻ repeat↻ repeatSTARTinclude <iostream>include <vector>include <algorithm>using namespace stdDEFINE knapsack(constvector<int>& weights, constvector<int>& values, int W)vector<int> dp(W + 1, 0)for (size_t i = 0; i <weights.size(); ++i)for (int w = W; w >=weights[i]; --w)dp[w] = max(dp[w], dp[w -weights[i]] + values[i])RETURN dp[W]DEFINE main()vector<int> weights = {1,3, 4, 5}vector<int> values = {1, 4,5, 7}cout << knapsack(weights,values, 7) << endlRETURN 0END
  • 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