shriyanshi24jindal

0 - 1 Knapsack Problem

Mar 28th, 2026
7
0
Never
Not a member of GistPad yet? Sign Up, it unlocks many cool features!
Java 19.34 KB | None | 0 0
  1. import java.util.*;
  2. class Solution {
  3. /** Recursive code */
  4. public int knapsack(int W, int val[], int wt[]) {
  5. return findMaxProfit(W, val, wt, val.length);
  6. }
  7.  
  8. public int findMaxProfit(int W, int val[], int wt[], int n)
  9. {
  10. if(n == 0 || W == 0)
  11. return 0;
  12.  
  13. if(wt[n-1] <= W)
  14. {
  15. // put the current weight into bag
  16. int pick = val[n-1] + findMaxProfit(W-wt[n-1], val, wt, n-1);
  17. int notPick = findMaxProfit(W, val, wt, n-1);
  18. return Math.max(pick, notPick);
  19. }
  20. // when weight exceeds the max weight
  21. return findMaxProfit(W, val, wt, n-1);
  22. }
  23.  
  24. /** Memoization code */
  25. public int knapsack(int W, int val[], int wt[]) {
  26. int n = wt.length;
  27.  
  28. // define a matrix as changing paramaters are n and W
  29. int[][] t = new int[n+1][W+1];
  30. for(int i=0; i<n+1; i++)
  31. {
  32. Arrays.fill(t[i], -1);
  33. }
  34.  
  35. return findMaxProfit(W, val, wt, val.length, t);
  36. }
  37.  
  38. public int findMaxProfit(int W, int val[], int wt[], int n, int[][] t)
  39. {
  40. if(n == 0 || W == 0)
  41. return 0;
  42.  
  43. if(t[n][W] != -1)
  44. return t[n][W];
  45.  
  46. if(wt[n-1] <= W)
  47. {
  48. // put the current weight into bag
  49. int pick = val[n-1] + findMaxProfit(W-wt[n-1], val, wt, n-1, t);
  50. int notPick = findMaxProfit(W, val, wt, n-1, t);
  51. t[n][W] = Math.max(pick, notPick);
  52. return t[n][W];
  53. }
  54. // when weight exceeds the max weight
  55. t[n][W] = findMaxProfit(W, val, wt, n-1, t);
  56. return t[n][W];
  57. }
  58.  
  59.  
  60. /** Top-down approach */
  61. public int knapsack(int W, int val[], int wt[]) {
  62. int n = wt.length;
  63.  
  64. // define a matrix as changing paramaters are n and W
  65. int[][] t = new int[n+1][W+1];
  66.  
  67. // intialise the matrix according to base condition
  68. for(int i=0; i<n+1; i++)
  69. {
  70. for(int j=0; j<W+1; j++)
  71. {
  72. if(i==0 || j==0)
  73. t[i][j] = 0;
  74. }
  75. }
  76.  
  77. for(int i=1; i<n+1; i++)
  78. {
  79. for(int j=1; j<W+1; j++)
  80. {
  81. if(wt[i-1] <= j)
  82. {
  83. int weight = wt[i-1];
  84. int pick = val[i-1] + t[i-1][j - weight];
  85. int notPick = t[i-1][j];
  86. t[i][j] = Math.max(pick, notPick);
  87. }
  88. else
  89. t[i][j] = t[i-1][j];
  90. }
  91. }
  92. return t[n][W];
  93. }
  94. }
RAW Paste Data Copied