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

Unbounded Knapsack

Fill capacities while allowing each item to be chosen repeatedly, exposing the loop-order difference from 0/1 Knapsack.

Core idea

Each item type may be chosen repeatedly. When a state takes the current item, its remainder stays on the same row instead of moving to the previous-item row.

Read the visualization

Every matrix cell compares skipping the item with taking one copy plus the best value at the smaller capacity. The highlighted dependency reveals why reuse is allowed.

0123456
∅0000000
A0
B0
C0

Initialize zero value for every capacity before considering any item type.

1function completeKnapsack(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][c - w[i - 1]] + v[i - 1]); // take cell choose current row i
11 }
12 }
13 }
14 return dp[m][W];
15}
capacity6
itemA( duplicate 2, value 5) B( duplicate 3, value 6) C( duplicate 4, value 7)
1 / 20

Complexity and tradeoffs

Time: O(nW). Space: O(nW). A one-dimensional table uses O(W) space when capacities iterate upward for reusable items.

Invariant: After finishing item row i, every capacity stores the best value obtainable from unlimited copies of the first i item types.

Where it fits

Unbounded Knapsack models repeatable purchases, cutting, and resource composition. Reverse the one-dimensional capacity loop to recover the at-most-once 0/1 variant.