I need help un identifying error in my code. I tried below code for input
int capacity = 1000;
int[] weights = {123, 456, 678, 908, 145, 657, 376, 892, 708, 224, 674, 235, 671, 443, 777, 333, 999, 111, 345, 567, 234, 876};
int[] values = {543, 133, 543, 555, 567, 223, 445, 564, 456, 243, 567, 323, 465, 344, 355, 123, 344, 234, 455, 123, 456, 237};
public static int helper(int capacity, int[] weights, int[] values, int[][] dp, int curWeight, int curVal, int idx) {
if (curWeight > capacity) return 0;
if (idx == weights.length) {
return curVal;
}
if (dp[idx][curWeight] != -1) return dp[idx][curWeight];
int ans1 = helper(capacity, weights, values, dp, curWeight + weights[idx], curVal + values[idx], idx + 1);
int ans2 = helper(capacity, weights, values, dp, curWeight, curVal, idx + 1);
dp[idx][curWeight] = Math.max(ans1, ans2);
return dp[idx][curWeight];
}
public static int findMaxKnapsackProfit(int capacity, int[] weights, int[] values) {
int[][] dp = new int[weights.length + 1][capacity + 1];
for (int[] temp : dp)
Arrays.fill(temp, -1);
int ans = helper(capacity, weights, values, dp, 0, 0, 0);
return ans;
}
It’s giving me answer 2245 instead of 2255. I am not sure what am I doing wrong.