fork download
  1. // A Dynamic Programming based solution for 0-1 Knapsack problem
  2. class Knapsack
  3. {
  4.  
  5. // A utility function that returns maximum of two integers
  6. static int max(int a, int b) { return (a > b)? a : b; }
  7.  
  8. // Returns the maximum value that can be put in a knapsack of capacity W
  9. static int knapSack(int W, int wt[], int val[], int n)
  10. {
  11. int i, w;
  12. int K[][] = new int[n+1][W+1];
  13.  
  14. // Build table K[][] in bottom up manner
  15. for (i = 0; i <= n; i++)
  16. {
  17. for (w = 0; w <= W; w++)
  18. {
  19. if (i==0 || w==0)
  20. K[i][w] = 0;
  21. else if (wt[i-1] <= w)
  22. K[i][w] = max(val[i-1] + K[i-1][w-wt[i-1]], K[i-1][w]);
  23. else
  24. K[i][w] = K[i-1][w];
  25. }
  26. }
  27.  
  28. for (int p = 0; p <=n; p++) {
  29. for (int q = 0; q <=W; q++) {
  30. System.out.print(K[p][q] + ", ");
  31. }
  32. System.out.println();
  33. }
  34. return K[n][W];
  35. }
  36.  
  37.  
  38. // Driver program to test above function
  39. public static void main(String args[])
  40. {
  41. int val[] = new int[]{60, 100, 120};
  42. int wt[] = new int[]{1, 2, 3};
  43. int W = 5;
  44. int n = val.length;
  45. System.out.println(knapSack(W, wt, val, n));
  46. }
  47. }
  48. /*This code is contributed by Rajat Mishra */
Success #stdin #stdout 0.04s 4386816KB
stdin
Standard input is empty
stdout
0, 0, 0, 0, 0, 0, 
0, 60, 60, 60, 60, 60, 
0, 60, 100, 160, 160, 160, 
0, 60, 100, 160, 180, 220, 
220