{"id":895,"date":"2025-08-13T19:44:59","date_gmt":"2025-08-13T14:14:59","guid":{"rendered":"https:\/\/codeanddebug.in\/blog\/?p=895"},"modified":"2025-08-13T19:45:00","modified_gmt":"2025-08-13T14:15:00","slug":"0-1-knapsack-problem","status":"publish","type":"post","link":"https:\/\/codeanddebug.in\/blog\/0-1-knapsack-problem\/","title":{"rendered":"0 &#8211; 1 Knapsack Problem | 5 DP Solutions in Python"},"content":{"rendered":"\n<p>Given&nbsp;<strong>n<\/strong>&nbsp;items, each with a specific&nbsp;<strong>weight<\/strong>&nbsp;and&nbsp;<strong>value<\/strong>, and a knapsack with a capacity of&nbsp;<strong>W<\/strong>, the task is to put the items in the knapsack such that the&nbsp;<strong>sum of weights of the items &lt;= W<\/strong>&nbsp;and the&nbsp;<strong>sum of values&nbsp;<\/strong>associated with them is&nbsp;<strong>maximized<\/strong>.&nbsp;<\/p>\n\n\n\n<p>Here&#8217;s the [<strong><a href=\"https:\/\/www.geeksforgeeks.org\/problems\/0-1-knapsack-problem0945\/1\" target=\"_blank\" rel=\"noreferrer noopener\"><mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-vivid-purple-color\"><span style=\"text-decoration: underline;\">Problem Link<\/span><\/mark><\/a><\/strong>] to begin with.<\/p>\n\n\n\n<p><strong>Note:&nbsp;<\/strong>You can either place an item entirely in the bag or leave it out entirely. Also, each item is available in&nbsp;<strong>single&nbsp;<\/strong>quantity.<\/p>\n\n\n\n<p><strong>Examples :<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>Input: <\/strong>W = 4, <code>val[]<\/code> = [1, 2, 3], <code>wt[]<\/code> = [4, 5, 1] <br><strong>Output: <\/strong>3<br><strong>Explanation: <\/strong>Choose the last item, which weighs 1 unit and has a value of 3.<\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>Input:<\/strong> W = 3, <code>val[]<\/code> = [1, 2, 3], <code>wt[]<\/code> = [4, 5, 6] <br><strong>Output: <\/strong>0<br><strong>Explanation: <\/strong>Every item has a weight exceeding the knapsack's capacity (3).<\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>Input:<\/strong> W = 5, <code>val[]<\/code> = [10, 40, 30, 50], <code>wt[]<\/code> = [5, 4, 2, 3] <br><strong>Output: <\/strong>80<br><strong>Explanation: <\/strong>Choose the third item (value 30, weight 2) and the last item (value 50, weight 3) for a total value of 80.<\/pre>\n\n\n\n<p><strong>Constraints:<\/strong><br>2 \u2264 val.size() = wt.size() \u2264 10<sup>3<\/sup><br>1 \u2264 W \u2264&nbsp;10<sup>3<\/sup><br>1 \u2264 val[i] \u2264&nbsp;10<sup>3<\/sup><br>1 \u2264 wt[i] \u2264&nbsp;10<sup>3<\/sup><\/p>\n\n\n<div style=\"max-width: -moz-fit-content; \" class=\"wp-block-ub-table-of-contents-block ub_table-of-contents ub_table-of-contents-collapsed\" id=\"ub_table-of-contents-2fb5ee66-7ef6-4280-9985-7b9d873d9abc\" data-linktodivider=\"false\" data-showtext=\"show\" data-hidetext=\"hide\" data-scrolltype=\"auto\" data-enablesmoothscroll=\"true\" data-initiallyhideonmobile=\"true\" data-initiallyshow=\"false\"><div class=\"ub_table-of-contents-header-container\" style=\"\">\n\t\t\t<div class=\"ub_table-of-contents-header\" style=\"text-align: left; \">\n\t\t\t\t<div class=\"ub_table-of-contents-title\">Contents:<\/div>\n\t\t\t\t<div class=\"ub_table-of-contents-header-toggle\">\n\t\t\t<div class=\"ub_table-of-contents-toggle\" style=\"\">\n\t\t\t\u00a0[<a class=\"ub_table-of-contents-toggle-link\" href=\"#\" style=\"\">show<\/a>]\n\t\t\t<\/div>\n\t\t<\/div>\n\t\t\t<\/div>\n\t\t<\/div><div class=\"ub_table-of-contents-extra-container\" style=\"\">\n\t\t\t<div class=\"ub_table-of-contents-container ub_table-of-contents-1-column ub-hide\">\n\t\t\t\t<ul style=\"\"><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/0-1-knapsack-problem\/#0-solution-1-recursion-brute-force\" style=\"\">Solution 1: Recursion (Brute Force)<\/a><ul><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/0-1-knapsack-problem\/#1-intuition-and-approach\" style=\"\">Intuition and Approach<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/0-1-knapsack-problem\/#2-code-implementation\" style=\"\">Code Implementation<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/0-1-knapsack-problem\/#3-code-explanation\" style=\"\">Code Explanation<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/0-1-knapsack-problem\/#4-time-and-space-complexity\" style=\"\">Time and Space Complexity<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/0-1-knapsack-problem\/#5-conclusion\" style=\"\">Conclusion<\/a><\/li><\/ul><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/0-1-knapsack-problem\/#6-solution-2-memoization-top-down-dp\" style=\"\">Solution 2: Memoization (Top-Down DP)<\/a><ul><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/0-1-knapsack-problem\/#7-intuition-and-approach\" style=\"\">Intuition and Approach<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/0-1-knapsack-problem\/#8-code-implementation\" style=\"\">Code Implementation<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/0-1-knapsack-problem\/#9-code-explanation\" style=\"\">Code Explanation<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/0-1-knapsack-problem\/#10-time-and-space-complexity\" style=\"\">Time and Space Complexity<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/0-1-knapsack-problem\/#11-conclusion\" style=\"\">Conclusion<\/a><\/li><\/ul><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/0-1-knapsack-problem\/#12-solution-3-tabulation-bottom-up-dp\" style=\"\">Solution 3: Tabulation (Bottom-Up DP)<\/a><ul><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/0-1-knapsack-problem\/#13-intuition-and-approach\" style=\"\">Intuition and Approach<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/0-1-knapsack-problem\/#14-code-implementation\" style=\"\">Code Implementation<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/0-1-knapsack-problem\/#15-code-explanation\" style=\"\">Code Explanation<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/0-1-knapsack-problem\/#16-time-and-space-complexity\" style=\"\">Time and Space Complexity<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/0-1-knapsack-problem\/#17-conclusion\" style=\"\">Conclusion<\/a><\/li><\/ul><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/0-1-knapsack-problem\/#18-solution-4-space-optimization-using-2-one-dimensional-arrays\" style=\"\">Solution 4: Space Optimization using 2 One-Dimensional Arrays<\/a><ul><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/0-1-knapsack-problem\/#19-intuition-and-approach\" style=\"\">Intuition and Approach<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/0-1-knapsack-problem\/#20-code-implementation\" style=\"\">Code Implementation<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/0-1-knapsack-problem\/#21-code-explanation\" style=\"\">Code Explanation<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/0-1-knapsack-problem\/#22-time-and-space-complexity\" style=\"\">Time and Space Complexity<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/0-1-knapsack-problem\/#23-conclusion\" style=\"\">Conclusion<\/a><\/li><\/ul><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/0-1-knapsack-problem\/#24-solution-5-space-optimization-using-a-single-1d-array\" style=\"\">Solution 5: Space Optimization using a Single 1D Array<\/a><ul><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/0-1-knapsack-problem\/#25-intuition-and-approach\" style=\"\">Intuition and Approach<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/0-1-knapsack-problem\/#26-code-implementation\" style=\"\">Code Implementation<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/0-1-knapsack-problem\/#27-code-explanation\" style=\"\">Code Explanation<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/0-1-knapsack-problem\/#28-time-and-space-complexity\" style=\"\">Time and Space Complexity<\/a><\/li><\/ul><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/0-1-knapsack-problem\/#29-final-notes-and-tips\" style=\"\">Final Notes and Tips<\/a><\/li><\/ul>\n\t\t\t<\/div>\n\t\t<\/div><\/div>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"0-solution-1-recursion-brute-force\">Solution 1: Recursion (Brute Force)<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"1-intuition-and-approach\">Intuition and Approach<\/h3>\n\n\n\n<p>At each item index:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>If the item fits (<strong>wt[index] \u2264 W<\/strong>), consider:\n<ul class=\"wp-block-list\">\n<li>pick = val[index] + best for remaining capacity (<strong>W \u2212 wt[index]<\/strong>) with previous items<\/li>\n\n\n\n<li>not_pick = best without taking this item<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li>Take&nbsp;<strong>max(pick, not_pick)<\/strong>.<\/li>\n\n\n\n<li>Base case: at index 0, if it fits, return its value; else&nbsp;<strong>0<\/strong>.<\/li>\n<\/ul>\n\n\n\n<p>This explores all subsets and forms the basis for memoization.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"2-code-implementation\">Code Implementation<\/h3>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.5rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" data-code=\"class Solution:\n    def solve(self, index, W, val, wt):\n        # Base: only first item available\n        if index == 0:\n            if wt[index] &lt;= W:\n                return val[index]\n            return 0\n        # If current item doesn't fit, can't pick it\n        if wt[index] &gt; W:\n            pick = float(&quot;-inf&quot;)\n        else:\n            # Option to pick current item\n            pick = val[index] + self.solve(index - 1, W - wt[index], val, wt)\n        # Option to not pick current item\n        not_pick = 0 + self.solve(index - 1, W, val, wt)\n        # Max of both choices\n        return max(pick, not_pick)\n\n    def knapsack(self, W, val, wt):\n        n = len(wt)\n        return self.solve(n - 1, W, val, wt)\" style=\"color:#D4D4D4;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki dark-plus\" style=\"background-color: #1E1E1E\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #569CD6\">class<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #4EC9B0\">Solution<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    <\/span><span style=\"color: #569CD6\">def<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">solve<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #9CDCFE\">self<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">index<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">W<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">val<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">wt<\/span><span style=\"color: #D4D4D4\">):<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #6A9955\"># Base: only first item available<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">if<\/span><span style=\"color: #D4D4D4\"> index == <\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            <\/span><span style=\"color: #C586C0\">if<\/span><span style=\"color: #D4D4D4\"> wt[index] &lt;= W:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                <\/span><span style=\"color: #C586C0\">return<\/span><span style=\"color: #D4D4D4\"> val[index]<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            <\/span><span style=\"color: #C586C0\">return<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #B5CEA8\">0<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #6A9955\"># If current item doesn&#39;t fit, can&#39;t pick it<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">if<\/span><span style=\"color: #D4D4D4\"> wt[index] &gt; W:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            pick = <\/span><span style=\"color: #4EC9B0\">float<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #CE9178\">&quot;-inf&quot;<\/span><span style=\"color: #D4D4D4\">)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">else<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            <\/span><span style=\"color: #6A9955\"># Option to pick current item<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            pick = val[index] + <\/span><span style=\"color: #569CD6\">self<\/span><span style=\"color: #D4D4D4\">.solve(index - <\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">, W - wt[index], val, wt)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #6A9955\"># Option to not pick current item<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        not_pick = <\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\"> + <\/span><span style=\"color: #569CD6\">self<\/span><span style=\"color: #D4D4D4\">.solve(index - <\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">, W, val, wt)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #6A9955\"># Max of both choices<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">return<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">max<\/span><span style=\"color: #D4D4D4\">(pick, not_pick)<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    <\/span><span style=\"color: #569CD6\">def<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">knapsack<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #9CDCFE\">self<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">W<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">val<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">wt<\/span><span style=\"color: #D4D4D4\">):<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        n = <\/span><span style=\"color: #DCDCAA\">len<\/span><span style=\"color: #D4D4D4\">(wt)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">return<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #569CD6\">self<\/span><span style=\"color: #D4D4D4\">.solve(n - <\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">, W, val, wt)<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"3-code-explanation\">Code Explanation<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Recursively tries&nbsp;<strong>both decisions<\/strong>&nbsp;where feasible and returns the&nbsp;<strong>maximum achievable value<\/strong>.<\/li>\n\n\n\n<li>The base case&nbsp;<strong>anchors<\/strong>&nbsp;the recursion at the first item.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"4-time-and-space-complexity\">Time and Space Complexity<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Precise:&nbsp;<strong>Time O(2^n)<\/strong>,&nbsp;<strong>Space O(n)<\/strong>&nbsp;recursion depth.<\/li>\n\n\n\n<li>Simplified:&nbsp;<strong>Exponential time<\/strong>;&nbsp;<strong>linear stack space<\/strong>.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"5-conclusion\">Conclusion<\/h3>\n\n\n\n<p>Great for&nbsp;<strong>understanding the choice structure<\/strong>, but too slow for larger&nbsp;<strong>n<\/strong>&nbsp;or&nbsp;<strong>W<\/strong>.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"6-solution-2-memoization-top-down-dp\">Solution 2: Memoization (Top-Down DP)<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"7-intuition-and-approach\">Intuition and Approach<\/h3>\n\n\n\n<p>The same&nbsp;<strong>(index, W)<\/strong>&nbsp;states repeat frequently.&nbsp;<strong>Cache<\/strong>&nbsp;results in a&nbsp;<strong>2D dp<\/strong>&nbsp;table to avoid recomputation:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>dp[index][W] stores the&nbsp;<strong>best value<\/strong>&nbsp;achievable considering items up to index with capacity W.<\/li>\n\n\n\n<li>Before computing,&nbsp;<strong>return cached value<\/strong>&nbsp;if available.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"8-code-implementation\">Code Implementation<\/h3>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.5rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" data-code=\"class Solution:\n    def solve(self, index, W, val, wt, dp):\n        # Base: first item\n        if index == 0:\n            if wt[index] &lt;= W:\n                return val[index]\n            return 0\n        # Cached result\n        if dp[index][W] != -1:\n            return dp[index][W]\n        # Decision: pick if it fits, else -inf\n        if wt[index] &gt; W:\n            pick = float(&quot;-inf&quot;)\n        else:\n            pick = val[index] + self.solve(index - 1, W - wt[index], val, wt, dp)\n        not_pick = 0 + self.solve(index - 1, W, val, wt, dp)\n        dp[index][W] = max(pick, not_pick)\n        return dp[index][W]\n\n    def knapsack(self, W, val, wt):\n        n = len(wt)\n        dp = [[-1 for _ in range(0, W + 1)] for _ in range(n)]\n        return self.solve(n - 1, W, val, wt, dp)\" style=\"color:#D4D4D4;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki dark-plus\" style=\"background-color: #1E1E1E\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #569CD6\">class<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #4EC9B0\">Solution<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    <\/span><span style=\"color: #569CD6\">def<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">solve<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #9CDCFE\">self<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">index<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">W<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">val<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">wt<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">dp<\/span><span style=\"color: #D4D4D4\">):<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #6A9955\"># Base: first item<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">if<\/span><span style=\"color: #D4D4D4\"> index == <\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            <\/span><span style=\"color: #C586C0\">if<\/span><span style=\"color: #D4D4D4\"> wt[index] &lt;= W:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                <\/span><span style=\"color: #C586C0\">return<\/span><span style=\"color: #D4D4D4\"> val[index]<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            <\/span><span style=\"color: #C586C0\">return<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #B5CEA8\">0<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #6A9955\"># Cached result<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">if<\/span><span style=\"color: #D4D4D4\"> dp[index][W] != -<\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            <\/span><span style=\"color: #C586C0\">return<\/span><span style=\"color: #D4D4D4\"> dp[index][W]<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #6A9955\"># Decision: pick if it fits, else -inf<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">if<\/span><span style=\"color: #D4D4D4\"> wt[index] &gt; W:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            pick = <\/span><span style=\"color: #4EC9B0\">float<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #CE9178\">&quot;-inf&quot;<\/span><span style=\"color: #D4D4D4\">)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">else<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            pick = val[index] + <\/span><span style=\"color: #569CD6\">self<\/span><span style=\"color: #D4D4D4\">.solve(index - <\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">, W - wt[index], val, wt, dp)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        not_pick = <\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\"> + <\/span><span style=\"color: #569CD6\">self<\/span><span style=\"color: #D4D4D4\">.solve(index - <\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">, W, val, wt, dp)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        dp[index][W] = <\/span><span style=\"color: #DCDCAA\">max<\/span><span style=\"color: #D4D4D4\">(pick, not_pick)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">return<\/span><span style=\"color: #D4D4D4\"> dp[index][W]<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    <\/span><span style=\"color: #569CD6\">def<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">knapsack<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #9CDCFE\">self<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">W<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">val<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">wt<\/span><span style=\"color: #D4D4D4\">):<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        n = <\/span><span style=\"color: #DCDCAA\">len<\/span><span style=\"color: #D4D4D4\">(wt)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        dp = [[-<\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #C586C0\">for<\/span><span style=\"color: #D4D4D4\"> _ <\/span><span style=\"color: #C586C0\">in<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">range<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">, W + <\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">)] <\/span><span style=\"color: #C586C0\">for<\/span><span style=\"color: #D4D4D4\"> _ <\/span><span style=\"color: #C586C0\">in<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">range<\/span><span style=\"color: #D4D4D4\">(n)]<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">return<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #569CD6\">self<\/span><span style=\"color: #D4D4D4\">.solve(n - <\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">, W, val, wt, dp)<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"9-code-explanation\">Code Explanation<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Stores results for each&nbsp;<strong>state<\/strong>&nbsp;to ensure each is&nbsp;<strong>solved once<\/strong>.<\/li>\n\n\n\n<li>Converts&nbsp;<strong>exponential recursion<\/strong>&nbsp;into&nbsp;<strong>polynomial time<\/strong>.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"10-time-and-space-complexity\">Time and Space Complexity<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Precise:&nbsp;<strong>Time O(n \u00d7 W)<\/strong>,&nbsp;<strong>Space O(n \u00d7 W)<\/strong>&nbsp;for dp +&nbsp;<strong>O(n)<\/strong>&nbsp;stack.<\/li>\n\n\n\n<li>Simplified:&nbsp;<strong>Polynomial time and space<\/strong>; suitable for typical constraints.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"11-conclusion\">Conclusion<\/h3>\n\n\n\n<p>Ideal upgrade over pure recursion, retaining&nbsp;<strong>clarity<\/strong>&nbsp;while being&nbsp;<strong>efficient<\/strong>.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"12-solution-3-tabulation-bottom-up-dp\">Solution 3: Tabulation (Bottom-Up DP)<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"13-intuition-and-approach\">Intuition and Approach<\/h3>\n\n\n\n<p>Iteratively build&nbsp;<strong>dp<\/strong>&nbsp;where dp[i][w] is the&nbsp;<strong>max value<\/strong>&nbsp;using items up to index i with capacity w.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Initialize first row: for all capacities&nbsp;<strong>w \u2265 wt<\/strong>, dp[w] =&nbsp;<strong>val<\/strong>.<\/li>\n\n\n\n<li>Transition:\n<ul class=\"wp-block-list\">\n<li>If&nbsp;<strong>wt[i] \u2264 w<\/strong>: pick = val[i] + dp[i\u22121][w \u2212 wt[i]]<\/li>\n\n\n\n<li>not_pick = dp[i\u22121][w]<\/li>\n\n\n\n<li>dp[i][w] =&nbsp;<strong>max(pick, not_pick)<\/strong><\/li>\n<\/ul>\n<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"14-code-implementation\">Code Implementation<\/h3>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.5rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" data-code=\"class Solution:\n    def knapsack(self, W, val, wt):\n        n = len(wt)\n        # dp[i][w] -&gt; max value using items up to i with capacity w\n        dp = [[0 for _ in range(0, W + 1)] for _ in range(n)]\n        # Initialize first item row\n        for w in range(0, W + 1):\n            if wt &lt;= w:\n                dp[w] = val\n        # Fill table\n        for index in range(1, n):\n            for W_ in range(0, W + 1):\n                if wt[index] &gt; W_:\n                    pick = float(&quot;-inf&quot;)\n                else:\n                    pick = val[index] + dp[index - 1][W_ - wt[index]]\n                not_pick = 0 + dp[index - 1][W_]\n                dp[index][W_] = max(pick, not_pick)\n        return dp[n - 1][W]\" style=\"color:#D4D4D4;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki dark-plus\" style=\"background-color: #1E1E1E\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #569CD6\">class<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #4EC9B0\">Solution<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    <\/span><span style=\"color: #569CD6\">def<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">knapsack<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #9CDCFE\">self<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">W<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">val<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">wt<\/span><span style=\"color: #D4D4D4\">):<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        n = <\/span><span style=\"color: #DCDCAA\">len<\/span><span style=\"color: #D4D4D4\">(wt)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #6A9955\"># dp[i][w] -&gt; max value using items up to i with capacity w<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        dp = [[<\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #C586C0\">for<\/span><span style=\"color: #D4D4D4\"> _ <\/span><span style=\"color: #C586C0\">in<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">range<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">, W + <\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">)] <\/span><span style=\"color: #C586C0\">for<\/span><span style=\"color: #D4D4D4\"> _ <\/span><span style=\"color: #C586C0\">in<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">range<\/span><span style=\"color: #D4D4D4\">(n)]<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #6A9955\"># Initialize first item row<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">for<\/span><span style=\"color: #D4D4D4\"> w <\/span><span style=\"color: #C586C0\">in<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">range<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">, W + <\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">):<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            <\/span><span style=\"color: #C586C0\">if<\/span><span style=\"color: #D4D4D4\"> wt &lt;= w:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                dp[w] = val<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #6A9955\"># Fill table<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">for<\/span><span style=\"color: #D4D4D4\"> index <\/span><span style=\"color: #C586C0\">in<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">range<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">, n):<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            <\/span><span style=\"color: #C586C0\">for<\/span><span style=\"color: #D4D4D4\"> W_ <\/span><span style=\"color: #C586C0\">in<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">range<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">, W + <\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">):<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                <\/span><span style=\"color: #C586C0\">if<\/span><span style=\"color: #D4D4D4\"> wt[index] &gt; W_:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                    pick = <\/span><span style=\"color: #4EC9B0\">float<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #CE9178\">&quot;-inf&quot;<\/span><span style=\"color: #D4D4D4\">)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                <\/span><span style=\"color: #C586C0\">else<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                    pick = val[index] + dp[index - <\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">][W_ - wt[index]]<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                not_pick = <\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\"> + dp[index - <\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">][W_]<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                dp[index][W_] = <\/span><span style=\"color: #DCDCAA\">max<\/span><span style=\"color: #D4D4D4\">(pick, not_pick)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">return<\/span><span style=\"color: #D4D4D4\"> dp[n - <\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">][W]<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"15-code-explanation\">Code Explanation<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Bottom-up computation<\/strong>&nbsp;ensures all subproblems are solved once in increasing order of&nbsp;<strong>i<\/strong>&nbsp;and&nbsp;<strong>capacity<\/strong>.<\/li>\n\n\n\n<li>Final answer resides at&nbsp;<strong>dp[n\u22121][W]<\/strong>.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"16-time-and-space-complexity\">Time and Space Complexity<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Precise:&nbsp;<strong>Time O(n \u00d7 W)<\/strong>,&nbsp;<strong>Space O(n \u00d7 W)<\/strong>.<\/li>\n\n\n\n<li>Simplified:&nbsp;<strong>Polynomial time and space<\/strong>; easy to trace and debug.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"17-conclusion\">Conclusion<\/h3>\n\n\n\n<p>A&nbsp;<strong>robust, iterative DP<\/strong>&nbsp;that\u2019s straightforward to implement and reason about.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"18-solution-4-space-optimization-using-2-one-dimensional-arrays\">Solution 4: Space Optimization using 2 One-Dimensional Arrays<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"19-intuition-and-approach\">Intuition and Approach<\/h3>\n\n\n\n<p>Each row depends only on the&nbsp;<strong>previous row<\/strong>, so keep just two 1D arrays:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>prev<\/strong>&nbsp;for dp[i\u22121][\u00b7] and&nbsp;<strong>curr<\/strong>&nbsp;for dp[i][\u00b7].<\/li>\n\n\n\n<li>After finishing a row, assign&nbsp;<strong>prev = curr<\/strong>.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"20-code-implementation\">Code Implementation<\/h3>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.5rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" data-code=\"class Solution:\n    def knapsack(self, W, val, wt):\n        n = len(wt)\n        prev = [0 for _ in range(0, W + 1)]\n        # Initialize first item row\n        for w in range(0, W + 1):\n            if wt &lt;= w:\n                prev[w] = val\n        # Build next rows\n        for index in range(1, n):\n            curr = [0 for _ in range(0, W + 1)]\n            for W_ in range(0, W + 1):\n                if wt[index] &gt; W_:\n                    pick = float(&quot;-inf&quot;)\n                else:\n                    pick = val[index] + prev[W_ - wt[index]]\n                not_pick = 0 + prev[W_]\n                curr[W_] = max(pick, not_pick)\n            prev = curr\n        return prev[W]\" style=\"color:#D4D4D4;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki dark-plus\" style=\"background-color: #1E1E1E\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #569CD6\">class<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #4EC9B0\">Solution<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    <\/span><span style=\"color: #569CD6\">def<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">knapsack<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #9CDCFE\">self<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">W<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">val<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">wt<\/span><span style=\"color: #D4D4D4\">):<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        n = <\/span><span style=\"color: #DCDCAA\">len<\/span><span style=\"color: #D4D4D4\">(wt)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        prev = [<\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #C586C0\">for<\/span><span style=\"color: #D4D4D4\"> _ <\/span><span style=\"color: #C586C0\">in<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">range<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">, W + <\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">)]<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #6A9955\"># Initialize first item row<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">for<\/span><span style=\"color: #D4D4D4\"> w <\/span><span style=\"color: #C586C0\">in<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">range<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">, W + <\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">):<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            <\/span><span style=\"color: #C586C0\">if<\/span><span style=\"color: #D4D4D4\"> wt &lt;= w:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                prev[w] = val<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #6A9955\"># Build next rows<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">for<\/span><span style=\"color: #D4D4D4\"> index <\/span><span style=\"color: #C586C0\">in<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">range<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">, n):<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            curr = [<\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #C586C0\">for<\/span><span style=\"color: #D4D4D4\"> _ <\/span><span style=\"color: #C586C0\">in<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">range<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">, W + <\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">)]<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            <\/span><span style=\"color: #C586C0\">for<\/span><span style=\"color: #D4D4D4\"> W_ <\/span><span style=\"color: #C586C0\">in<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">range<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">, W + <\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">):<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                <\/span><span style=\"color: #C586C0\">if<\/span><span style=\"color: #D4D4D4\"> wt[index] &gt; W_:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                    pick = <\/span><span style=\"color: #4EC9B0\">float<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #CE9178\">&quot;-inf&quot;<\/span><span style=\"color: #D4D4D4\">)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                <\/span><span style=\"color: #C586C0\">else<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                    pick = val[index] + prev[W_ - wt[index]]<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                not_pick = <\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\"> + prev[W_]<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                curr[W_] = <\/span><span style=\"color: #DCDCAA\">max<\/span><span style=\"color: #D4D4D4\">(pick, not_pick)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            prev = curr<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">return<\/span><span style=\"color: #D4D4D4\"> prev[W]<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"21-code-explanation\">Code Explanation<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Reduces space from&nbsp;<strong>O(n \u00d7 W)<\/strong>&nbsp;to&nbsp;<strong>O(W)<\/strong>&nbsp;while preserving all transitions.<\/li>\n\n\n\n<li>Maintains correctness by using&nbsp;<strong>the previous row only<\/strong>.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"22-time-and-space-complexity\">Time and Space Complexity<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Precise:&nbsp;<strong>Time O(n \u00d7 W)<\/strong>,&nbsp;<strong>Space O(W)<\/strong>.<\/li>\n\n\n\n<li>Simplified: Same time,&nbsp;<strong>linear space<\/strong>&nbsp;in capacity.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"23-conclusion\">Conclusion<\/h3>\n\n\n\n<p>A&nbsp;<strong>practical<\/strong>&nbsp;and&nbsp;<strong>memory-efficient<\/strong>&nbsp;improvement that\u2019s often required in interviews.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"24-solution-5-space-optimization-using-a-single-1d-array\">Solution 5: Space Optimization using a Single 1D Array<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"25-intuition-and-approach\">Intuition and Approach<\/h3>\n\n\n\n<p>Update the same array in&nbsp;<strong>reverse capacity order<\/strong>&nbsp;to avoid overwriting needed values:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Iterate&nbsp;<strong>W_ from W down to 0<\/strong>&nbsp;for each item to ensure dp[w \u2212 wt[i]] still refers to the previous iteration\u2019s state.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"26-code-implementation\">Code Implementation<\/h3>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.5rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" data-code=\"class Solution:\n    def knapsack(self, W, val, wt):\n        n = len(wt)\n        prev = [0 for _ in range(0, W + 1)]\n        # Initialize first item\n        for w in range(0, W + 1):\n            if wt &lt;= w:\n                prev[w] = val\n        # Single-array optimization: iterate capacity backward\n        for index in range(1, n):\n            for W_ in range(W, -1, -1):\n                if wt[index] &gt; W_:\n                    pick = float(&quot;-inf&quot;)\n                else:\n                    pick = val[index] + prev[W_ - wt[index]]\n                not_pick = 0 + prev[W_]\n                prev[W_] = max(pick, not_pick)\n        return prev[W]\" style=\"color:#D4D4D4;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki dark-plus\" style=\"background-color: #1E1E1E\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #569CD6\">class<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #4EC9B0\">Solution<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    <\/span><span style=\"color: #569CD6\">def<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">knapsack<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #9CDCFE\">self<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">W<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">val<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">wt<\/span><span style=\"color: #D4D4D4\">):<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        n = <\/span><span style=\"color: #DCDCAA\">len<\/span><span style=\"color: #D4D4D4\">(wt)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        prev = [<\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #C586C0\">for<\/span><span style=\"color: #D4D4D4\"> _ <\/span><span style=\"color: #C586C0\">in<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">range<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">, W + <\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">)]<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #6A9955\"># Initialize first item<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">for<\/span><span style=\"color: #D4D4D4\"> w <\/span><span style=\"color: #C586C0\">in<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">range<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">, W + <\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">):<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            <\/span><span style=\"color: #C586C0\">if<\/span><span style=\"color: #D4D4D4\"> wt &lt;= w:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                prev[w] = val<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #6A9955\"># Single-array optimization: iterate capacity backward<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">for<\/span><span style=\"color: #D4D4D4\"> index <\/span><span style=\"color: #C586C0\">in<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">range<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">, n):<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            <\/span><span style=\"color: #C586C0\">for<\/span><span style=\"color: #D4D4D4\"> W_ <\/span><span style=\"color: #C586C0\">in<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">range<\/span><span style=\"color: #D4D4D4\">(W, -<\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">, -<\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">):<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                <\/span><span style=\"color: #C586C0\">if<\/span><span style=\"color: #D4D4D4\"> wt[index] &gt; W_:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                    pick = <\/span><span style=\"color: #4EC9B0\">float<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #CE9178\">&quot;-inf&quot;<\/span><span style=\"color: #D4D4D4\">)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                <\/span><span style=\"color: #C586C0\">else<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                    pick = val[index] + prev[W_ - wt[index]]<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                not_pick = <\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\"> + prev[W_]<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                prev[W_] = <\/span><span style=\"color: #DCDCAA\">max<\/span><span style=\"color: #D4D4D4\">(pick, not_pick)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">return<\/span><span style=\"color: #D4D4D4\"> prev[W]<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"27-code-explanation\">Code Explanation<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Backward iteration<\/strong>&nbsp;ensures correctness by preventing intra-row contamination.<\/li>\n\n\n\n<li>Achieves the optimal&nbsp;<strong>O(W) space<\/strong>&nbsp;with clean logic.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"28-time-and-space-complexity\">Time and Space Complexity<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Precise:&nbsp;<strong>Time O(n \u00d7 W)<\/strong>,&nbsp;<strong>Space O(W)<\/strong>.<\/li>\n\n\n\n<li>Simplified:&nbsp;<strong>Best practical DP<\/strong>&nbsp;for classic 0-1 Knapsack.<\/li>\n<\/ul>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"29-final-notes-and-tips\">Final Notes and Tips<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Base initialization<\/strong>&nbsp;for the first item row is crucial to seed the DP correctly.<\/li>\n\n\n\n<li>Using&nbsp;<strong>float(&#8220;-inf&#8221;)<\/strong>&nbsp;for \u201ccannot pick\u201d keeps max logic clean; alternatively, conditionally skip computing pick.<\/li>\n\n\n\n<li>The&nbsp;<strong>single-array backward iteration<\/strong>&nbsp;is the optimal space pattern for 0-1 knapsack; forward iteration would incorrectly reuse updated states.<\/li>\n\n\n\n<li>For very large&nbsp;<strong>W<\/strong>, consider value-based DP or alternative heuristics, but for typical constraints, these DP formulations are&nbsp;<strong>standard<\/strong>.<\/li>\n<\/ul>\n\n\n\n<p>Mastering these five formulations, especially the transition from&nbsp;<strong>recursion<\/strong>&nbsp;to&nbsp;<strong>O(W) space<\/strong>, builds strong&nbsp;<strong>dynamic programming intuition<\/strong>&nbsp;and prepares for a wide range of&nbsp;<strong>knapsack-like problems<\/strong>.<\/p>\n\n\n\n<div class=\"wp-block-buttons is-content-justification-center is-layout-flex wp-container-core-buttons-is-layout-16018d1d wp-block-buttons-is-layout-flex\">\n<div class=\"wp-block-button\"><a class=\"wp-block-button__link wp-element-button\" href=\"https:\/\/codeanddebug.in\/course\/zero-to-hero-python-dsa\" target=\"_blank\" rel=\"noreferrer noopener\">Join our Advance DSA COURSE<\/a><\/div>\n<\/div>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<p><em>For any changes to the article, kindly email at <a href=\"mailto:code@codeanddebug.in\" target=\"_blank\" rel=\"noreferrer noopener\">code@codeanddebug.in<\/a> or contact us at <a href=\"tel:+91-9712928220\" target=\"_blank\" rel=\"noreferrer noopener\">+91-9712928220<\/a>.<\/em><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Given&nbsp;n&nbsp;items, each with a specific&nbsp;weight&nbsp;and&nbsp;value, and a knapsack with a capacity of&nbsp;W, the task is to put the items in the knapsack such that the&nbsp;sum of weights of the items &lt;= W&nbsp;and the&nbsp;sum of values&nbsp;associated with them is&nbsp;maximized.&nbsp; Here&#8217;s the [Problem Link] to begin with. Note:&nbsp;You can either place an item entirely in the bag<\/p>\n","protected":false},"author":1,"featured_media":896,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"ub_ctt_via":"","footnotes":""},"categories":[3,5],"tags":[39,18],"class_list":{"0":"post-895","1":"post","2":"type-post","3":"status-publish","4":"format-standard","5":"has-post-thumbnail","7":"category-data-structures-and-algorithm","8":"category-expert","9":"tag-dynamic-programming-on-subsequence","10":"tag-hard"},"featured_image_src":"https:\/\/codeanddebug.in\/blog\/wp-content\/uploads\/2025\/08\/0-1-knapsack-problem-featured-image.png","author_info":{"display_name":"codeanddebug","author_link":"https:\/\/codeanddebug.in\/blog\/author\/codeanddebug\/"},"_links":{"self":[{"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts\/895","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/comments?post=895"}],"version-history":[{"count":3,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts\/895\/revisions"}],"predecessor-version":[{"id":901,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts\/895\/revisions\/901"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/media\/896"}],"wp:attachment":[{"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/media?parent=895"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/categories?post=895"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/tags?post=895"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}