Those who cannot remember the past are condemned to repeat it.
0-1 Knapsack
Code
// A utility function that returns// maximum of two integersstaticintmax(inta,intb){return(a>b)?a:b;}// Returns the maximum value that// can be put in a knapsack of// capacity WstaticintknapSack(intW,intwt[],intval[],intn){// Base Caseif(n==0||W==0)return0;// If weight of the nth item is// more than Knapsack capacity W,// then this item cannot be included// in the optimal solutionif(wt[n-1]>W)returnknapSack(W,wt,val,n-1);// Return the maximum of two cases:// (1) nth item included// (2) not includedelsereturnmax(val[n-1]+knapSack(W-wt[n-1],wt,val,n-1),knapSack(W,wt,val,n-1));}// Driver codepublicstaticvoidmain(Stringargs[]){intval[]=newint[]{120,60,100};intwt[]=newint[]{10,20,30};intW=50;intn=val.length;System.out.println(knapSack(W,wt,val,n));}