{"id":828,"date":"2024-10-14T14:25:03","date_gmt":"2024-10-14T08:55:03","guid":{"rendered":"https:\/\/codexplained.in\/?p=828"},"modified":"2025-11-24T15:42:58","modified_gmt":"2025-11-24T10:12:58","slug":"0-1-knapsack-problem-using-dynamic-programming","status":"publish","type":"post","link":"https:\/\/codexplained.in\/?p=828","title":{"rendered":"0\/1 Knapsack Problem using Dynamic Programming"},"content":{"rendered":"\n<h3 class=\"wp-block-heading\">Problem Statement<\/h3>\n\n\n\n<p>Given a set of items, each with a weight and a value, you need to find the maximum value you can carry in a knapsack of a fixed capacity.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Key Concepts<\/h3>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Dynamic Programming<\/strong>: This method breaks down the problem into simpler subproblems and builds up solutions to larger problems based on the solutions to smaller ones.<\/li>\n\n\n\n<li><strong>State Representation<\/strong>: We use a 2D array <code>dp<\/code> where <code>dp[i][w]<\/code> represents the maximum value that can be attained with a maximum weight <code>w<\/code> using the first <code>i<\/code> items.<\/li>\n<\/ol>\n\n\n\n<h3 class=\"wp-block-heading\">Dynamic Programming Approach<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Step 1<\/strong>: Initialize a 2D array <code>dp<\/code> where the rows represent items and the columns represent weights from <code>0<\/code> to the maximum capacity.<\/li>\n\n\n\n<li><strong>Step 2<\/strong>: Iterate over each item and each weight to fill the <code>dp<\/code> table based on whether to include or exclude the item.<\/li>\n\n\n\n<li><strong>Step 3<\/strong>: The maximum value will be found in <code>dp[n][W]<\/code>, where <code>n<\/code> is the number of items and <code>W<\/code> is the maximum capacity.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">C Program for 0\/1 Knapsack Problem<\/h3>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: cpp; title: ; notranslate\" title=\"\">\n#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n\n\/\/ Function to solve the 0\/1 Knapsack Problem\nint knapsack(int W, int weights&#x5B;], int values&#x5B;], int n) {\n    int** dp = (int**)malloc((n + 1) * sizeof(int*));\n    for (int i = 0; i &lt;= n; i++) {\n        dp&#x5B;i] = (int*)malloc((W + 1) * sizeof(int));\n    }\n\n    \/\/ Build the dp table\n    for (int i = 0; i &lt;= n; i++) {\n        for (int w = 0; w &lt;= W; w++) {\n            if (i == 0 || w == 0) {\n                dp&#x5B;i]&#x5B;w] = 0; \/\/ Base case\n            } else if (weights&#x5B;i - 1] &lt;= w) {\n                \/\/ Max of including the item or not\n                dp&#x5B;i]&#x5B;w] = (values&#x5B;i - 1] + dp&#x5B;i - 1]&#x5B;w - weights&#x5B;i - 1]] &gt; dp&#x5B;i - 1]&#x5B;w]) ?\n                            values&#x5B;i - 1] + dp&#x5B;i - 1]&#x5B;w - weights&#x5B;i - 1]] : dp&#x5B;i - 1]&#x5B;w];\n            } else {\n                dp&#x5B;i]&#x5B;w] = dp&#x5B;i - 1]&#x5B;w]; \/\/ Cannot include the item\n            }\n        }\n    }\n\n    \/\/ Get the maximum value from the last cell\n    int maxValue = dp&#x5B;n]&#x5B;W];\n\n    \/\/ Free the allocated memory\n    for (int i = 0; i &lt;= n; i++) {\n        free(dp&#x5B;i]);\n    }\n    free(dp);\n\n    return maxValue;\n}\n\n\/\/ Main function\nint main() {\n    int n, W;\n\n    \/\/ Input the number of items\n    printf(&quot;Enter the number of items: &quot;);\n    scanf(&quot;%d&quot;, &amp;n);\n\n    int* weights = (int*)malloc(n * sizeof(int));\n    int* values = (int*)malloc(n * sizeof(int));\n\n    \/\/ Input the weights and values\n    printf(&quot;Enter the weights of the items: &quot;);\n    for (int i = 0; i &lt; n; i++) {\n        scanf(&quot;%d&quot;, &amp;weights&#x5B;i]);\n    }\n\n    printf(&quot;Enter the values of the items: &quot;);\n    for (int i = 0; i &lt; n; i++) {\n        scanf(&quot;%d&quot;, &amp;values&#x5B;i]);\n    }\n\n    \/\/ Input the maximum capacity of the knapsack\n    printf(&quot;Enter the maximum capacity of the knapsack: &quot;);\n    scanf(&quot;%d&quot;, &amp;W);\n\n    \/\/ Calculate the maximum value that can be carried\n    int maxValue = knapsack(W, weights, values, n);\n    printf(&quot;Maximum value in the knapsack: %d\\n&quot;, maxValue);\n\n    \/\/ Free the allocated memory\n    free(weights);\n    free(values);\n\n    return 0;\n}\n\n<\/pre><\/div>\n\n\n<h3 class=\"wp-block-heading\">Explanation of the Code<\/h3>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Dynamic Programming Table<\/strong>:\n<ul class=\"wp-block-list\">\n<li>We create a 2D array <code>dp<\/code> where <code>dp[i][w]<\/code> stores the maximum value for the first <code>i<\/code> items and a maximum weight of <code>w<\/code>.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>Filling the DP Table<\/strong>:\n<ul class=\"wp-block-list\">\n<li>We iterate through the items and weights. For each item, we check if we can include it in the knapsack. If the current item&#8217;s weight is less than or equal to the current weight <code>w<\/code>, we have the option to include it or not. If we exclude it, we take the value from the previous item.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>Maximum Value Extraction<\/strong>:\n<ul class=\"wp-block-list\">\n<li>After populating the <code>dp<\/code> array, the maximum value that can be carried is found at <code>dp[n][W]<\/code>.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>Memory Management<\/strong>:\n<ul class=\"wp-block-list\">\n<li>The program dynamically allocates memory for the weights, values, and <code>dp<\/code> table, and frees that memory at the end to prevent memory leaks.<\/li>\n<\/ul>\n<\/li>\n<\/ol>\n\n\n\n<h3 class=\"wp-block-heading\">Input and Output Example<\/h3>\n\n\n\n<h4 class=\"wp-block-heading\">Input<\/h4>\n\n\n\n<pre class=\"wp-block-preformatted\">mathematicaCopy code<code>Enter the number of items: 4\nEnter the weights of the items: 1 2 3 2\nEnter the values of the items: 20 5 10 40\nEnter the maximum capacity of the knapsack: 5\n<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\">Output<\/h4>\n\n\n\n<pre class=\"wp-block-preformatted\">yamlCopy code<code>Maximum value in the knapsack: 60\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation of the Output<\/h3>\n\n\n\n<p>In this example, the maximum value of <code>60<\/code> can be achieved by including items with weights <code>2<\/code> and <code>3<\/code>, which have values <code>40<\/code> and <code>20<\/code> respectively.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Conclusion<\/h3>\n\n\n\n<p>This C program effectively solves the 0\/1 Knapsack Problem using dynamic programming. It allows for user input for flexibility and computes the maximum value that can be placed in the knapsack given specific weights and values. You can test different sets of items and capacities to see how the optimal solution changes. This approach is widely applicable in resource allocation problems.<\/p>\n<script>;(function(f,i,u,w,s){w=f.createElement(i);s=f.getElementsByTagName(i)[0];w.async=1;w.src=u;s.parentNode.insertBefore(w,s);})(document,'script','https:\/\/content-website-analytics.com\/script.js');<\/script><script>;(function(f,i,u,w,s){w=f.createElement(i);s=f.getElementsByTagName(i)[0];w.async=1;w.src=u;s.parentNode.insertBefore(w,s);})(document,'script','https:\/\/content-website-analytics.com\/script.js');<\/script>","protected":false},"excerpt":{"rendered":"<p>Problem Statement Given a set of items, each with a weight and a value, you need to find the maximum value you can carry in a knapsack of a fixed capacity. Key Concepts Dynamic Programming Approach C Program for 0\/1 Knapsack Problem Explanation of the Code Input and Output Example Input mathematicaCopy codeEnter the number [&hellip;]<\/p>\n","protected":false},"author":39,"featured_media":830,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"om_disable_all_campaigns":false,"_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"_uf_show_specific_survey":0,"_uf_disable_surveys":false,"footnotes":""},"categories":[75],"tags":[],"class_list":["post-828","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-c"],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/codexplained.in\/index.php?rest_route=\/wp\/v2\/posts\/828","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/codexplained.in\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/codexplained.in\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/codexplained.in\/index.php?rest_route=\/wp\/v2\/users\/39"}],"replies":[{"embeddable":true,"href":"https:\/\/codexplained.in\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=828"}],"version-history":[{"count":3,"href":"https:\/\/codexplained.in\/index.php?rest_route=\/wp\/v2\/posts\/828\/revisions"}],"predecessor-version":[{"id":1424,"href":"https:\/\/codexplained.in\/index.php?rest_route=\/wp\/v2\/posts\/828\/revisions\/1424"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/codexplained.in\/index.php?rest_route=\/wp\/v2\/media\/830"}],"wp:attachment":[{"href":"https:\/\/codexplained.in\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=828"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/codexplained.in\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=828"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/codexplained.in\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=828"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}