class Solution { /** Recursion */ public int knapSack(int val[], int wt[], int capacity) { int n = wt.length; return findMaxProfit(capacity, wt, val, n); } public int findMaxProfit(int W, int[] wt, int[] val, int n) { // Base case: no items or no remaining capacity if(n == 0 || W == 0) return 0; if(wt[n-1] <= W) { // pick the item (n stays the same because we can pick it again) int pick = val[n-1] + findMaxProfit(W - wt[n-1], wt, val, n); // do not pick the item (move to next item) int notPick = findMaxProfit(W, wt, val, n-1); return Math.max(pick, notPick); } // current weight exceed max weight, cannot pick the item return findMaxProfit(W, wt, val, n-1); } /** Memoization */ public int knapSack(int val[], int wt[], int capacity) { int n = wt.length; int[][] t = new int[n+1][capacity+1]; for(int i=0; i