0-1 Knapsack Problem using Dynamic Programming

This is a C++ Program that Solves 0 1 Knapsack Problem using Dynamic Programming technique.

Problem Description

Given weights and values of n items, put these items in a knapsack of capacity M to get the maximum total value in the knapsack.

Note that, you can select items, the sum of whose weight is less than or equal to the capacity of knapsack, W.

Problem Solution

The problem is to find a subset of items such that –

  1. the sum of weight of all the items in the subset should be less than or equal to knapsack capacity
  2. out of all subsets that satisfy criteria 1 above, the desired subset is the one in which the sum values of its items is maximum.

consider this example-
n=3
w[]=3 2 1
v[]=5 3 4

M=5

Create a matrix of order (n+1)*(M+1), ie. knapsack[n+1][M+1]
knapsack[i][j]=maximum attainable value of items in the knapsack with i available items and capacity of knapsack being j.

advertisement
advertisement

Initialize –
knapsack[0][j]=0 for 0<=j<=M
knapsack[i][0]=0 for 0<=i<=n
Now, start filling the matrix row wise, following the given recursive formula –

knapsack[i][j]= knapsack[i-1][j] , if w[i]>j
max{knapsack[i-1][j], v[i]+knapsack[i-1][j-w[i]] } , if w[i]<=j

The time complexity of this solution is O(n*M).

Expected Input and Output

Case-1:

number of items, n=4
 
weight of items, w[]=2 3 4 5
value of items,  v[]=3 4 5 6
 
capacity of knapsack, M=5
 
maximum attainable value of items=7 
by collecting first and second item in the knapsack

Case-2:

 
n=3
w[]=3 2 1
v[]=5 3 4
 
M=5
 
maximum attainable value of items=9 
by collecting first and last item in the knapsack

Case-3:

 
n=5
w[]=1 2 3 2 2
v[]=8 4 0 4 3
 
M=4
 
maximum attainable value of items=13
Program/Source Code for recursive solution

Here is source code of the C++ Program to Solve 0 1 Knapsack Problem. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.

advertisement
  1. #include<iostream>
  2. using namespace std;
  3.  
  4. //function to recursive check every subset of items
  5. int knapsack(int w[], int p[], int n, int M)
  6. {
  7.     //In every pass, we can either include nth item or not
  8.  
  9.     //if the capacity of knapsack is left to NIL, no value can be attained
  10.     if(M==0)
  11.         return 0;
  12.  
  13.     //if no more items are left, no value can be attained
  14.     if(n==0)
  15.         return 0;
  16.  
  17.     //if current item, weighs more than the capacity of knapsack, it can not be included
  18.     if(w[n-1]>M)
  19.         return knapsack(w,p,n-1,M);
  20.  
  21.     //else select the maximum value of once including the current item and once not including it
  22.     return max(knapsack(w,p,n-1,M),p[n-1]+knapsack(w,p,n-1,M-w[n-1]));
  23. }
  24.  
  25. int main()
  26. {
  27.     int i,n;
  28.     int M;  //capacity of knapsack
  29.  
  30.     cout<<"Enter the no. of items ";
  31.     cin>>n;
  32.  
  33.     int w[n];  //weight of items
  34.     int p[n];  //value of items
  35.  
  36.     cout<<"Enter the weight and price of all items"<<endl;
  37.     for(i=0;i<n;i++)
  38.     {
  39.         cin>>w[i]>>p[i];
  40.     }
  41.  
  42.     cout<<"enter the capacity of knapsack  ";
  43.     cin>>M;
  44.  
  45.     cout<<"The maximum value of items that can be put into knapsack is "<<knapsack(w,p,n,M);
  46.  
  47.     return 0;
  48. }
Program/Source Code for DP solution

Here is source code of the C++ Program to Solve 0 1 Knapsack Problem. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. #include<bits/stdc++.h>
  2. using namespace std;
  3.  
  4. int knapsack_dp(int n, int M, int w[], int p[])
  5. {
  6.     int i,j;
  7.  
  8.     //create a matrix to memoize the values using dynamic programming
  9.     int knapsack[n+1][M+1];
  10.  
  11.     //knapsack[i][j] denotes the maximum attainable value of items in knpasack with i available 
  12.     //items and capacity of knapsack being j
  13.  
  14.     //initializing knapsack[0][j]=0 for 0<=j<=M
  15.     //because if there is no item, no value can be attained
  16.     for(j=0;j<=M;j++)
  17.         knapsack[0][j]=0;
  18.  
  19.     //initializing knapsack[i][0]=0 for 0<=i<=n,
  20.     //because in a bag of zero capacity, no item can be placed
  21.     for(i=0;i<=n;i++)
  22.         knapsack[i][0]=0;
  23.  
  24.     //now, filling the matrix in bottom up manner
  25.     for(i=1;i<=n;i++)
  26.     {
  27.         for(j=1;j<=M;j++)
  28.         {
  29.             //check if the weight of current item i is less than or equal to the capacity of sack,
  30.             //take maximum of once including the current item and once not including
  31.             if(w[i-1]<=j)
  32.             {
  33.                 knapsack[i][j]=max(knapsack[i-1][j],p[i-1]+knapsack[i-1][j-w[i-1]]);
  34.             }
  35.  
  36.             //can not include the current item in this case
  37.             else
  38.             {
  39.                 knapsack[i][j]=knapsack[i-1][j];
  40.             }
  41.         }
  42.     }
  43.  
  44.  
  45.     return knapsack[n][M];
  46.  
  47.  
  48. }
  49.  
  50. int main()
  51. {
  52.     int i,j;
  53.     int n;  //number of items
  54.     int M;  //capacity of knapsack
  55.  
  56.     cout<<"Enter the no. of items ";
  57.     cin>>n;
  58.  
  59.     int w[n];  //weight of items
  60.     int p[n];  //value of items
  61.  
  62.     cout<<"Enter the weight and price of all items"<<endl;
  63.     for(i=0;i<n;i++)
  64.     {
  65.         cin>>w[i]>>p[i];
  66.     }
  67.  
  68.     cout<<"enter the capacity of knapsack  ";
  69.     cin>>M;
  70.  
  71.  
  72.     int result=knapsack_dp(n,M,w,p);
  73.  
  74.     //the maximum value will be given by knasack[n][M], ie. using n items with capacity M
  75.     cout<<"The maximum value of items that can be put into knapsack is "<<result;
  76.  
  77.     return 0;
  78. }
Program Explanation

In the main function, we ask the user to input number of items, weight & price of each item and the capacity of knapsack. We pass this values to the function knapsack_dp as parameters. This function will calculate the expected result and return it. The returned value will be displayed.

advertisement
Runtime Test Cases
 
Case-1:
$ g++ knapsack.cpp
$ ./a.out
Enter the no. of items 4
Enter the weight and price of all items
2 3
3 4
4 5
5 6
enter the capacity of knapsack  5
The maximum value of items that can be put into knapsack is 7

Sanfoundry Global Education & Learning Series – Dynamic Programming Problems.
To practice all Dynamic Programming Problems, here is complete set of 100+ Problems and Solutions.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.