0 - 1 Knapsack Problem | Practice | GeeksforGeeks

You are given weights and values of N items, put these items in a knapsack of capacity W to get the maximum total value in the knapsack. Note that we have only one quantity of each item.
In other words, given two integer arrays val[0..N-1] and wt[0..N-1] which represent values and weights associated with N items respectively. Also given an integer W which represents knapsack capacity, find out the maximum value subset of val[] such that sum of the weights of this subset is smaller than or equal to W. You cannot break an item, either pick the complete item or dont pick it (0-1 property).
Example 1:
Input:
N = 3
W = 4
values[] = {1,2,3}
weight[] = {4,5,1}
Output: 3

Example 2:
Input:
N = 3
W = 3
values[] = {1,2,3}
weight[] = {4,5,6}
Output: 0
Your Task:
Complete the function knapSack() which takes maximum capacity W, weight array wt[], value array val[], and the number of items n as a parameter and returns the maximum possible value you can get.
Expected Time Complexity: O(N*W).
Expected Auxiliary Space: O(N*W)
Constraints:
1 ≤ N ≤ 1000
1 ≤ W ≤ 1000
1 ≤ wt[i] ≤ 1000
1 ≤ v[i] ≤ 1000
0
itsmemritu14 hours ago
int knapSack(int W, int wt[], int val[], int n)    {       // Your code here      int dp[n+1][W+1];      for(int i=0 ;i<n+1 ;i++){          for(int j=0 ;j<W+1 ;j++){             if(i==0 or j==0){                 dp[i][j]=0;                 continue;             }              if(wt[i-1]<=j){                  dp[i][j]=max( (val[i-1]+ dp[i-1][j-wt[i-1]]) , (dp[i-1][j]) );              }              else{                  dp[i][j]=dp[i-1][j];              }          }      }      return dp[n][W];   }
+1
mr_coder99335 days ago
C++/Simple
Time Complexity:- O(n*W)
Space Complexity:- O(W)
Using Tabulation
int knapSack(int W, int wt[], int val[], int n) 
    { 
       vector<int> dp(W+1,0),temp(W+1);
       
        for(int i=0;i<n;i++){
            temp[0]=0;
            for(int j=1;j<=W;j++){
                temp[j]=dp[j];
                if(j>=wt[i]){
                	temp[j]=max(temp[j],
                    val[i]+dp[j-wt[i]]);
                }    
            }
            dp=temp;
        }    
       return dp[W];
    }
0
moaslam8261 week ago
c++ soln

int fun(int *value,int *weight,int n,int w,vector<vector<int>>&dp){
if(dp[n][w]!=-1) return dp[n][w];
 if(w==0) return dp[n][w]=0;
 if(n==0){
 	if(w-weight[0]<0) return 0;
 	else  return dp[n][w]=value[0];
 }
 if(w-weight[n]<0)
 return dp[n][w]=fun(value,weight,n-1,w,dp);
 else{
    int a=INT_MIN,b=INT_MIN;
    a=fun(value,weight,n-1,w,dp);
    b=fun(value,weight,n-1,w-weight[n],dp)+value[n];
    return dp[n][w]=max(a,b);
 }  
}
   
   
    int knapSack(int W, int wt[], int val[], int n) 
    {  
        // const int N=1e3+2;
        vector<vector<int>> dp(n+2,vector<int>(W+2,-1));
       return fun(val,wt,n-1,W,dp);
    }
0
vinamrajha1 week ago
int knapSack(int W, int wt[], int val[], int n) 
   { 
      // Your code here
      int dp[n+1][W+1];
      for(int i =0; i<=n; ++i)dp[i][0] =0;
      for(int i =0; i<=W; ++i)dp[0][i] =0;
      for(int i =1; i<=n; ++i){
          for(int j =1; j<=W; ++j){
              if(wt[i-1]>j) dp[i][j] = dp[i-1][j];
              else dp[i][j] = max(dp[i-1][j], val[i-1]+dp[i-1][j-wt[i-1]]);
          }
      }
      return dp[n][W];
   }
-2
2019011112 weeks ago
int knapSack(int W, int wt[], int val[], int n) 
{ 
    int t[W+1]={0};
    for(int i=0;i<n;i++)
    {
        for(int j=W;j>=wt[i];j--)
        {
            t[j]=max(t[j],t[j-wt[i]]+val[i]);
        }
    }
    return t[W];
}
0
devashishbakare2 weeks ago
JAVA DP Tabulation
  static int knapSack(int cap, int wt[], int val[], int n) 
    { 
        
        if( n <= 0)
        return 0;
       
        //why we creating this space, what the reason of it?
        //creating this 2d array due to we have eigther pick or not pick conditon 
            //if I pick this weight how much profit I will got after adding my profit
            //if not then no need,hence 2d Array
        //we have to store the maximum profit we can get from given capasity
        //each cell is representing a maximum profit we get
       
        int dp[][] = new int[n+1][cap+1];
        
        //treavel through capcity we can store in knapsack
        for(int i = 1 ; i < dp.length ; i++)
        {//we are traversing form 1, coz zero index, means zero wt, we are not getting any value, so..
            for(int j = 1 ; j < dp[0].length ; j++)
            {
                
                //check whether this cell has a capacity to add new weight
                //if yes then add it and check whether profit is maximum or not
                if( j >= wt[i-1])
                {
                    //current val + previous possible value;
                    int temp = val[i-1] + dp[i-1][j - wt[i-1]];
                    //we have added selft weight then profit is maximum
                    //chcek if I add my weight what the profit 
                    if(temp > dp[i-1][j])
                        //if profit maximize then add to this cell
                        dp[i][j] = temp;
                    else
                    //we have not added self weight(val) and still  profit is maximum.
                    dp[i][j] = dp[i-1][j];
                 //if capcity of cell is not suffuciet to add this weight then carry the same pr   
                }else
                {
                    dp[i][j] = dp[i-1][j];
                    
                }
                
            }
        }
        
        return dp[n][cap];
    } 
 
+1
sanketbhagat3 weeks ago
SIMPEL JAVA SOLUTION
class Solution { 
    //Function to return max value that can be put in knapsack of capacity W.
    static int knapSack(int w, int wt[], int val[], int n) { 
         // your code here 
        int prev[] = new int[w+1];
        for(int i=0;i<n;i++){
            int curr[] = new int[w+1];
            for(int j=1;j<=w;j++){
                if(wt[i]<=j) curr[j] = Math.max(val[i]+prev[j-wt[i]],prev[j]);
                else curr[j] = prev[j];
            }
            prev = curr;
        }
        return prev[w];
    } 
}
0
kumarsuraj43 weeks ago
Space Optimised : 
 
int knapSack(int W, int wt[], int val[], int n) 
    { 
       // Your code here
        vector<int> dp(W+1,0);
        
        for(int i=0;i<n;i++)
        {
            for(int w=W;w>=0;w--)
            {
                if(w-wt[i]>=0)
                    dp[w] = max(dp[w],val[i] + dp[w-wt[i]]);
                else dp[w] = dp[w];
            }
        }
        return dp[W];
    }
0
09himanshusah1 month ago
#JavaScript Solution
class Solution 
{
    //Function to return max value that can be put in knapsack of capacity W.
    max(a,b){
        if(a > b) return a;
        else return b;
    }
    
    knapSack(W, wt, val, n)
    { 
       // code here
       let dp = [];
       for(let i = 0; i < n+1; i++) {
           dp[i] = [];
           for(let j = 0; j < W+1; j++) {
               if(i === 0 || j === 0) {
                   dp[i][j] = 0;
               }
           }
       }
       
        for(let i = 1; i < n+1; i++) {
           for(let j = 1; j < W+1; j++) {
               if(wt[i-1] <= j) {
                   dp[i][j] = this.max(val[i-1]+dp[i-1][j-wt[i-1]], dp[i-1][j]);
               } else {
                   dp[i][j] = dp[i-1][j];
               }
           }
        }
        return dp[n][W];
    }
}
0
adityagagtiwari1 month ago
here is the code friends if need any help understanding anything or want to do pair-programming reply this thread. 
I am solving the dp section of GFG SDE Sheet.
class Solution {    //Function to return max value that can be put in knapsack of capacity W.   static int knapSack(int W, int wt[], int val[], int n)    {         // your code here         int[][] dp = new int[n+1][W+1];        int max = 0;        for(int i=1;i<n+1;i++)        {            for(int j = 1 ; j<W+1;j++)            {                // is 0 case/we do not put it in the sack               dp[i][j] = dp[i-1][j];               //if weight is lesser than current weight under consideration then there is a chance to put the ith               //value in the sack. If adding this value i-1 is increasing the value then use it along with the  j - wt[i].               if(j>=wt[i-1])               {                   int diff = j-wt[i-1];                   dp[i][j] = Math.max(dp[i][j],(dp[i-1][j-wt[i-1]]+val[i-1]));               }            }        }        return dp[n][W];   } }
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.