06/04/2017

Geeksforgeeks Solution For " 0 - 1 Knapsack Problem "

GeeksforGeeks Solution For Hard Domain .Below You Can Find The Solution Of  School Basic ,Easy ,Medium . Or Hackerrank Solution You Can Also Direct Submit Your Solution to Geeksforgeeks Same Problem .You Need to login then you can submit you answers 

Problem :- 0 - 1 Knapsack Problem 

Submit Your Solution :- Click Here 

Solution :- 

#include<iostream>
using namespace std;
int max(int ,int ) ;
int Knapsack_Problem(int [],int [],int ,int ) ;
int main()
 {
 int t,no,w,val[100],weight[100],i ;
 cin>>t ;
 while(t--)
 {
     cin>>no ;
     cin>>w ;
    
     for(i=0;i<no;i++)
         cin>>val[i] ;
        
     for(i=0;i<no;i++)
         cin>>weight[i] ;
        
     no=Knapsack_Problem(val,weight,no,w) ;
     cout<<no<<endl ;
 }
 return 0;
}

int Knapsack_Problem(int val[],int weight[],int no,int w)
{
    int i,j ;
    int mat[no+1][w+1]={0} ;
   
    for(i=0;i<=no;i++)
        mat[i][0]=0 ;
       
    for(i=0;i<=w;i++)
        mat[0][i]=0 ;
   
    for(i=1;i<=no;i++)
    {
        for(j=1;j<=w;j++)
        {
            if(j>=weight[i-1])
            {
                mat[i][j]=max(mat[i-1][j],val[i-1]+mat[i-1][j-weight[i-1]]) ;
            }
            else if(i>1)
             mat[i][j]=mat[i-1][j] ;
        }
    }
    return mat[no][w] ;
}

int max(int a,int b)
{
 return a>b?a:b ;
}

Output:-



Geeksforgeeks Solution For " 0 - 1 Knapsack Problem "

Previous Post
Next Post

post written by:

Hi, I’m Ghanendra Yadav, SEO Expert, Professional Blogger, Programmer, and UI Developer. Get a Solution of More Than 500+ Programming Problems, and Practice All Programs in C, C++, and Java Languages. Get a Competitive Website Solution also Ie. Hackerrank Solutions and Geeksforgeeks Solutions. If You Are Interested to Learn a C Programming Language and You Don't Have Experience in Any Programming, You Should Start with a C Programming Language, Read: List of Format Specifiers in C.
Follow Me

0 Comments: