• Source
    1.  
    2.  
    3. class Ideone{
    4.  
    5. public static void main(String[] args){
    6. int val[] = {15, 9, 5, 10};
    7. int wt[] = {1, 3, 4, 5};
    8. int maxWeight = 8;
    9. System.out.println("Max value obtained from knapsack => "+ maxKnapSackValue(val, wt, maxWeight, val.length));
    10. System.out.println("Max value obtained form dp knapsack => "+ knapsackDPSolution(val, wt, maxWeight));
    11. }
    12.  
    13. private static int knapsackDPSolution(int[] val, int[] wt, int maxWeight){
    14. int[][] dp = new int[val.length+1][maxWeight+1];
    15. for(int i=0; i<=wt.length; i++){
    16. for(int w=0; w<=maxWeight; w++){
    17. if(i==0 || w==0){
    18. dp[i][w] = 0;
    19. }else if(wt[i-1] <= w){
    20. dp[i][w] = max(val[i-1]+dp[i-1][w-wt[i-1]], dp[i-1][w]);
    21. }else{
    22. dp[i][w] = dp[i-1][w];
    23. }
    24. }
    25. }
    26. return dp[wt.length][maxWeight];
    27. }
    28.  
    29. //Recursive solution
    30. private static int maxKnapSackValue(int[] val, int[] wt, int maxWeight, int n){
    31. if(n==0 || maxWeight == 0 ) return 0;
    32.  
    33. //If weight of nth item is more than max capacity, it cannot be inclded
    34. if(wt[n-1] > maxWeight) return maxKnapSackValue(val, wt, maxWeight, n-1);
    35. else return max(val[n-1] + maxKnapSackValue(val, wt, maxWeight-wt[n-1], n-1), maxKnapSackValue(val, wt, maxWeight, n-1));
    36. }
    37.  
    38. private static int max(int a, int b){
    39. return a>b?a:b;
    40. }
    41. }
    42.