shriyanshi24jindal

Knapsack with Duplicate Items

Mar 28th, 2026
15
0
Never
Not a member of GistPad yet? Sign Up, it unlocks many cool features!
Java 19.75 KB | None | 0 0
  1. class Solution {
  2. /** Recursion */
  3. public int knapSack(int val[], int wt[], int capacity) {
  4. int n = wt.length;
  5.  
  6. return findMaxProfit(capacity, wt, val, n);
  7. }
  8.  
  9. public int findMaxProfit(int W, int[] wt, int[] val, int n)
  10. {
  11. // Base case: no items or no remaining capacity
  12. if(n == 0 || W == 0)
  13. return 0;
  14.  
  15. if(wt[n-1] <= W)
  16. {
  17. // pick the item (n stays the same because we can pick it again)
  18. int pick = val[n-1] + findMaxProfit(W - wt[n-1], wt, val, n);
  19.  
  20. // do not pick the item (move to next item)
  21. int notPick = findMaxProfit(W, wt, val, n-1);
  22. return Math.max(pick, notPick);
  23. }
  24. // current weight exceed max weight, cannot pick the item
  25. return findMaxProfit(W, wt, val, n-1);
  26. }
  27.  
  28. /** Memoization */
  29. public int knapSack(int val[], int wt[], int capacity) {
  30. int n = wt.length;
  31.  
  32. int[][] t = new int[n+1][capacity+1];
  33. for(int i=0; i<n+1; i++)
  34. Arrays.fill(t[i], -1);
  35.  
  36. return findMaxProfit(capacity, wt, val, n, t);
  37. }
  38.  
  39. public int findMaxProfit(int W, int[] wt, int[] val, int n, int[][] t)
  40. {
  41. // Base case: no items or no remaining capacity
  42. if(n == 0 || W == 0)
  43. return 0;
  44.  
  45. if(t[n][W] != -1)
  46. return t[n][W];
  47.  
  48. if(wt[n-1] <= W)
  49. {
  50. // pick the item (n stays the same because we can pick it again)
  51. int pick = val[n-1] + findMaxProfit(W - wt[n-1], wt, val, n, t);
  52.  
  53. // do not pick the item (move to next item)
  54. int notPick = findMaxProfit(W, wt, val, n-1, t);
  55. t[n][W] = Math.max(pick, notPick);
  56. return t[n][W];
  57. }
  58. // current weight exceed max weight, cannot pick the item
  59. t[n][W] = findMaxProfit(W, wt, val, n-1, t);
  60. return t[n][W];
  61. }
  62.  
  63. /** Top-down approach */
  64. public int knapSack(int val[], int wt[], int capacity) {
  65. int n = wt.length;
  66.  
  67. int[][] t = new int[n+1][capacity+1];
  68.  
  69. // base condition: no items or no remaining capacity
  70. for(int i=0; i<n+1; i++)
  71. {
  72. for(int j=0; j<capacity+1; j++)
  73. {
  74. if(i == 0 || j == 0)
  75. t[i][j] = 0;
  76. }
  77. }
  78.  
  79. for(int i=1; i<n+1; i++)
  80. {
  81. for(int j=1; j<capacity+1; j++)
  82. {
  83. if(wt[i-1] <= j)
  84. {
  85. // pick the item (n stays the same because we can pick it again)
  86. int pick = val[i-1] + t[i][j - wt[i-1]];
  87. // do not pick the item (move to next item)
  88. int notPick = t[i-1][j];
  89. t[i][j] = Math.max(pick, notPick);
  90. }
  91. // current weight exceed max weight, cannot pick the item
  92. else
  93. t[i][j] = t[i-1][j];
  94. }
  95. }
  96. return t[n][capacity];
  97. }
  98. }
RAW Paste Data Copied