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
rajkumaryadav123
This comment was deleted.
0
kvatsadeo28 minutes ago
 public:
    //Function to return max value that can be put in knapsack of capacity W.
    int f(int tar,int wt[],int val[],int ind, vector<vector<int>> &dp){
        if(ind==0){
            if(wt[ind]<=tar) return val[ind];
            else return 0;
        }
        if(dp[ind][tar]!=-1) return dp[ind][tar];
        if(wt[ind]<=tar){
            return dp[ind][tar]=max(val[ind]+f(tar-wt[ind],wt,val,ind-1,dp),f(tar,wt,val,ind-1,dp));
        }else return dp[ind][tar]=f(tar,wt,val,ind-1,dp);
    }
    int knapSack(int W, int wt[], int val[], int n) 
    { 
       vector<vector<int>> dp(n,vector<int>(W+1,-1));
       return f(W,wt,val,n-1,dp);
    }
    tabulation:
    vector<vector<int>> dp(n,vector<int>(W+1,0));
       for(int ind=0;ind<n;ind++){
           for(int tar=0;tar<=W;tar++){
               if(ind==0){
                   if(wt[0]<=tar) dp[0][tar]=val[0];
                    else dp[ind][tar]= 0;
               }else{
                    if(wt[ind]<=tar){
                         dp[ind][tar]=max(val[ind]+dp[ind-1][tar-wt[ind]],dp[ind-1][tar]);
                   }else dp[ind][tar]=dp[ind-1][tar];
               }
           }
       }
       return dp[n-1][W];
 
0
pareekaditya0143 minutes ago
class Solution
{
    public:
    //Function to return max value that can be put in knapsack of capacity W. 
    
    // Using Memoization
    int knapSackMem(int W, int wt[], int val[], int n,vector<vector<int>> &t) 
    { 
        if(n == 0 || W == 0)
        return 0;
        
       if(t[n][W] != -1)return t[n][W];
       
       if(W >= wt[n-1])
       {
         return t[n][W] = max(val[n-1] + knapSackMem(W-wt[n-1],wt,val,n-1,t),knapSackMem(W,wt,val,n-1,t));
       }
       else 
       {
          return t[n][W] = knapSackMem(W,wt,val,n-1,t);
       }
    }
    
    //Using TopDown / Tabulation
    
    int knapSackTab(int W, int wt[], int val[], int n)
    {
        int t[n+1][W+1];
        
        //trasfer of recursive base case into tabulation
        for(int i=0;i<n+1;i++)
        {
            for(int j=0;j<W+1;j++)
            {
                if(i == 0 || j == 0)
                {
                    t[i][j] = 0;
                }
            }
        }
        
        for(int i=1;i<n+1;i++)
        {
            for(int j=1;j<W+1;j++)
            {
                if(wt[i-1] <= j)
                {
                    t[i][j] = max(val[i-1] + t[i-1][j-wt[i-1]],t[i-1][j]);
                }
                else
                {
                    t[i][j] = t[i-1][j];
                }
            }
        }
        return t[n][W];
        
    }
    
    int knapSack(int W, int wt[], int val[], int n) 
    { 
        // vector<vector<int>> t(n+1,vector<int>(W+1,-1));
        // return knapSackMem(W,wt,val,n,t);
        
        return knapSackTab(W,wt,val,n);
        
    }
};
0
orijitsen1231 hour ago
// { Driver Code Starts
#include<bits/stdc++.h>
using namespace std;


 // } Driver Code Ends
class Solution
{
    public:
    int solve(int W, int wt[], int val[], int n, vector<vector<int>>&dp)
    { 
       if(n==0 || W==0)
       {
           return 0;
       }
       
       if(dp[W][n]!=-1)
       {
           return dp[W][n];
       }
       
       if(wt[n-1] <= W)
       {
           return dp[W][n] = max( val[n-1] + solve(W-wt[n-1], wt, val, n-1, dp),
           solve(W, wt, val, n-1, dp));
       }
       else if(wt[n-1]>W)
       {
           return dp[W][n] = solve(W, wt, val, n-1, dp);
       }
    }
    //Function to return max value that can be put in knapsack of capacity W.
    int knapSack(int W, int wt[], int val[], int n) 
    { 
       // Your code here
      vector<vector<int>>dp(W+1,vector<int>(n+1,-1));
      int ans = solve(W, wt, val, n, dp);
      return ans;
    }
};

// { Driver Code Starts.

int main()
 {
    //taking total testcases
    int t;
    cin>>t;
    while(t--)
    {
        //reading number of elements and weight
        int n, w;
        cin>>n>>w;
        
        int val[n];
        int wt[n];
        
        //inserting the values
        for(int i=0;i<n;i++)
            cin>>val[i];
        
        //inserting the weights
        for(int i=0;i<n;i++)
            cin>>wt[i];
        Solution ob;
        //calling method knapSack()
        cout<<ob.knapSack(w, wt, val, n)<<endl;
        
    }
	return 0;
}  // } Driver Code Ends
0
rahultewari002 days ago
def knapSack(self,W, w, v, n):       dp = [[-1]*(W+1) for _ in range(n+1)]       def knapsack01(i,W):           if i==0 or W==0:               return 0           if dp[i][W]!=-1:               return dp[i][W]           if w[i-1]<=W:               dp[i][W] = max(v[i-1]+knapsack01(i-1,W-w[i-1]),knapsack01(i-1,W))               return dp[i][W]           elif w[i-1]>W:               dp[i][W] = knapsack01(i-1,W)               return dp[i][W]       return knapsack01(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.
Make sure you are not using ad-blockers.
Disable browser extensions.
We recommend using latest version of your browser for best experience.
Avoid using static/global variables in coding problems as your code is tested 
                                against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases in coding problems 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.