V

Algorithm Visualizer

ZHEN
Share on WeiboShare on XGitHub repositoryAuthor website
Learning ToolsAlgorithm Complexity ReferenceAlgorithm Learning Paths
Data StructuresArrayLinked ListStackQueue and DequeBinary Search TreeBinary HeapHash TableGraphTrieDisjoint Set UnionLRU CacheSkip ListSegment TreeB+ TreeBloom FilterFenwick Tree
SortingBubble SortCocktail Shaker SortBitonic SortSelection SortInsertion SortBinary Insertion SortShell SortMerge SortTop-Down Merge SortQuick SortThree-Way Quick SortDual-Pivot Quick SortHeap SortCounting SortRadix SortBucket Sort
Graph AlgorithmsDijkstra's Shortest PathKruskal's Minimum Spanning TreePrim's Minimum Spanning TreeBellman-Ford Shortest PathsTopological SortFloyd-WarshallStrongly Connected Components2-SATMaximum FlowBipartite MatchingLowest Common AncestorEulerian Path
Dynamic ProgrammingEdit Distance0/1 KnapsackUnbounded KnapsackLongest Common SubsequenceLongest Increasing SubsequenceCoin ChangeStone MergingTraveling Salesperson DPTree Dynamic ProgrammingDigit DPRerooting DP
Backtracking and SearchN-QueensSubsetsPermutationsCombination SumMaze Solving with DFSNumber of IslandsWord SearchSudoku SolverA* Search
StringsKMP String MatchingRabin-Karp String MatchingBoyer-Moore String MatchingManacher's Longest Palindromic SubstringSuffix ArrayLCP ArrayAho-Corasick AutomatonZ Function
Math and Number TheorySieve of EratosthenesLinear SieveEuclidean AlgorithmBinary ExponentiationExtended Euclidean AlgorithmChinese Remainder TheoremEuler's Totient FunctionMiller-Rabin Primality TestFast Fourier TransformPollard's Rho Factorization
Computational GeometryConvex HullRotating CalipersClosest Pair of PointsLine Segment IntersectionBentley-Ottmann Sweep Line
SearchingBinary SearchLower and Upper BoundSearch in a Rotated Sorted ArrayBinary Search on the AnswerTernary Search

0/1 Knapsack

Dynamic programming for choices under a capacity limit

Take an item or leave it

Each item has a weight and a value, and each item may be chosen at most once. Define dp[i][w] as the greatest value possible using the first i items with capacity w. This state turns an exponential collection of subsets into a table of reusable subproblems.

Read the two source cells

If an item is too heavy, copy the value from the row above. Otherwise compare skipping it with taking it: dp[i-1][w] versus dp[i-1][w-weight] + value. The highlighted cells show both sources for every decision. The bottom-right result is 7, produced by items A and B.

012345
∅000000
A0
B0
C0
D0

With no items or zero capacity, the best value is 0.

1function knapsack(w: number[], v: number[], W: number): number {
2 const m = w.length;
3 const dp = Array.from({ length: m + 1 }, () => Array(W + 1).fill(0));
4 for (let i = 1; i <= m; i++) {
5 for (let c = 1; c <= W; c++) {
6 if (w[i - 1] > c) {
7 dp[i][c] = dp[i - 1][c];
8 } else {
9 dp[i][c] = Math.max(
10 dp[i - 1][c], dp[i - 1][c - w[i - 1]] + v[i - 1]);
11 }
12 }
13 }
14 return dp[m][W];
15}
Capacity5
ItemsA(weight=2, value=3) B(weight=3, value=4) C(weight=4, value=5) D(weight=5, value=6)
1 / 22

Complexity and variations

The table has n * W states, so time and full-table space are O(nW). Because each row only depends on the previous row, a one-dimensional implementation can reduce space to O(W) by iterating capacities backward.

The 0/1 restriction is encoded by reading from the previous row. Complete Knapsack changes that source so the current item can be reused. Subset Sum and many resource-allocation models are close relatives of the same recurrence.