{"id":113,"date":"2026-11-13T12:31:41","date_gmt":"2026-11-13T04:31:41","guid":{"rendered":"https:\/\/hoho.live\/luda\/index.php\/2026\/11\/13\/how-0-1-knapsack-fills-a-capacity-row\/"},"modified":"2026-11-13T21:50:36","modified_gmt":"2026-11-13T13:50:36","slug":"how-0-1-knapsack-fills-a-capacity-row","status":"publish","type":"post","link":"https:\/\/hoho.live\/luda\/index.php\/2026\/11\/13\/how-0-1-knapsack-fills-a-capacity-row\/","title":{"rendered":"How 0-1 knapsack fills a capacity row"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\"><strong>Short answer:<\/strong> The <strong>0-1 knapsack<\/strong> problem takes each item at most once. With capacity W and n items, the cell dp[i][w] is the best value using the first i items and capacity w. The item is skipped, or it is taken when its weight fits, and the cell is the better of those two. Rolling the items one at a time, and scanning the capacity <strong>downward<\/strong>, keeps the recurrence in a single array of length W+1. Time is <strong>O(nW)<\/strong>, which is pseudo-polynomial.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>What the problem actually asks<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">A greedy sort by value density is optimal for the fractional knapsack and not for 0-1, where an item cannot be cut. The subset structure is optimal substructure on the remaining capacity: once an item is rejected or accepted, the rest of the problem is a smaller 0-1 knapsack. That is the recurrence.<\/p>\n\n\n<p class=\"wp-block-paragraph\">The downward scan is the implementation detail that enforces &#8220;at most once.&#8221; Scanning upward would let the same item be added again inside the same pass, which is the unbounded problem.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>What the algorithm guarantees<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">The answer is dp[W] after every item has been considered, and it is the maximum value that fits. Time is \u0398(nW). Memory is \u0398(W) with the rolling array, or \u0398(nW) if the decisions must be reconstructed. Reconstruction keeps a predecessor or a boolean take[i][w]. The algorithm assumes nonnegative integer weights. Real-valued weights do not index the array. Very large W makes the pseudo-polynomial bound unacceptable, and a meet-in-the-middle on n near 40, or an FPTAS, is the alternative.<\/p>\n\n\n<p class=\"wp-block-paragraph\">The same table with a different inner loop solves unbounded knapsack. Confusing the scan direction silently solves the wrong problem and still returns a plausible number.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>The working steps<\/strong><\/h4>\n\n<ol class=\"wp-block-list\">\n<li>Allocate dp[0..W], initially 0. A capacity of 0 holds nothing, and the empty set has value 0.<\/li>\n<li>For each item with value v and weight w, for t from W down to w, set dp[t] = max(dp[t], dp[t\u2212w] + v).<\/li>\n<li>The downward order reads dp[t\u2212w] from before this item was considered, so the item is used at most once.<\/li>\n<li>After all items, dp[W] is the optimum. To list the items, either store decisions or recompute which choice matched each cell.<\/li>\n<li>If several items share an identity and may each be used once, they are separate iterations of the outer loop, not one iteration with a count.<\/li>\n<\/ol>\n\n\n<p class=\"wp-block-paragraph\">O(nW) counts arithmetic on a capacity index. It is not polynomial in the bit length of W. Fractional knapsack, which may cut an item, is the density sort. Unbounded knapsack, which may repeat an item, is the upward scan. 0-1 is the downward scan.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>Approaches that look simpler and fail<\/strong><\/h4>\n\n<figure class=\"wp-block-table\">\n<table>\n<thead>\n<tr>\n<th>Approach<\/th>\n<th>Why it fails when the capacity loop runs upward<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>Scan t from w up to W while updating one item<\/td>\n<td>dp[t\u2212w] may already include this item. The pass solves the unbounded problem for that item and can pack it many times.<\/td>\n<\/tr>\n<tr>\n<td>Sort by value\/weight and take items while they fit<\/td>\n<td>That is optimal for fractional knapsack. A 0-1 counterexample is a heavy high-value item that should displace two light ones, or the reverse.<\/td>\n<\/tr>\n<tr>\n<td>Index the array by a real-valued weight<\/td>\n<td>The state is an integer capacity. Real weights need a different formulation, usually scaling or an exponential subset DP on n.<\/td>\n<\/tr>\n<tr>\n<td>Quote O(nW) as polynomial time<\/td>\n<td>W can be exponential in the input length. The bound is pseudo-polynomial, which is useful and not the same claim.<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<\/figure>\n\n\n<p class=\"wp-block-paragraph\">Repeating items belong to the unbounded knapsack scan. Cuttable items belong to the fractional density sort. A capacity large enough to make nW impossible, with n near 40, belongs to meet-in-the-middle. 0-1 knapsack is the downward DP.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>A working example<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">The Bash script and the Python script fill a 0-1 knapsack row from the high capacity downward, so each item is used at most once. Capacity 5, weights 2 3 4 5, values 3 4 5 6. Both print <code>7<\/code>.<\/p>\n\n<pre><code class=\"language-bash\">w=(2 3 4 5)\nv=(3 4 5 6)\nW=5\nfor ((c=0; c&lt;=W; c++)); do dp[c]=0; done\nn=${#w[@]}\nfor ((i=0; i&lt;n; i++)); do\n  for ((c=W; c&gt;=w[i]; c--)); do\n    alt=$(( dp[c-w[i]] + v[i] ))\n    if (( alt &gt; dp[c] )); then dp[c]=$alt; fi\n  done\ndone\necho &quot;${dp[W]}&quot;\n<\/code><\/pre>\n<pre><code class=\"language-python\">weights = [2, 3, 4, 5]\nvalues = [3, 4, 5, 6]\nW = 5\ndp = [0] * (W + 1)\nfor w, v in zip(weights, values):\n    for cap in range(W, w - 1, -1):\n        dp[cap] = max(dp[cap], dp[cap - w] + v)\nbest = 0\nitems = list(zip(weights, values))\n\ndef brute(i, cap):\n    global best\n    if i == len(items):\n        return 0\n    skip = brute(i + 1, cap)\n    w, v = items[i]\n    take = 0 if w &gt; cap else v + brute(i + 1, cap - w)\n    return max(skip, take)\n\nassert dp[W] == brute(0, W) == 7\nprint(dp[W])\n<\/code><\/pre>\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>Where it is used<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">The <strong>0-1 knapsack<\/strong> recurrence is the capital-budget and cargo-loading problem: each item is taken once, and the capacity row stores the best value. The unbounded coin-change recurrence is the sibling that allows repeats. Cryptographic key search is a different algorithm.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>When you can drop this algorithm<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">Drop the DP when W is huge and n is the smaller parameter. Use meet-in-the-middle or an approximation scheme. Keep the downward row when weights are integers, each item may be taken once, and nW fits.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>Why this stays published<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">We publish this so a search for 0-1 knapsack returns the downward capacity scan that keeps each item from being reused. <strong>0-1 knapsack fills a capacity array from the top downward, in O(nW) time, so each item is considered at most once.<\/strong><\/p>\n\n\n<p class=\"wp-block-paragraph\">\u672c\u6587\u7531 HoHo \u8207 AI \u5354\u4f5c\u6574\u7406\uff0c\u6700\u5f8c\u66f4\u65b0\u65bc 2026 \u5e74 11 \u6708 13 \u65e5\u3002<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Short answer: The 0-1 knapsack problem takes each item at most once. With capacity W and n items, the cell dp[i][w] is the best value using the first i items and capacity w. The item is skipped, or it is taken when its weight fits, and the cell is&hellip;<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[30,33],"tags":[],"class_list":["post-113","post","type-post","status-publish","format-standard","hentry","category-algorithms","category-dynamic-programming"],"_links":{"self":[{"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts\/113","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/comments?post=113"}],"version-history":[{"count":2,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts\/113\/revisions"}],"predecessor-version":[{"id":512,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts\/113\/revisions\/512"}],"wp:attachment":[{"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/media?parent=113"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/categories?post=113"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/tags?post=113"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}