Skip to content

Optimize and Format Knapsack Memoization Algorithm #5685

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 10 commits into from
Oct 12, 2024
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package com.thealgorithms.dynamicprogramming;

import java.util.Arrays;

/**
* Recursive Solution for 0-1 knapsack with memoization
* This method is basically an extension to the recursive approach so that we
Expand All @@ -15,10 +17,8 @@ int knapSack(int capacity, int[] weights, int[] profits, int numOfItems) {
int[][] dpTable = new int[numOfItems + 1][capacity + 1];

// Loop to initially fill the table with -1
for (int i = 0; i < numOfItems + 1; i++) {
for (int j = 0; j < capacity + 1; j++) {
dpTable[i][j] = -1;
}
for (int[] table : dpTable) {
Arrays.fill(table, -1);
}

return solveKnapsackRecursive(capacity, weights, profits, numOfItems, dpTable);
Expand All @@ -38,7 +38,6 @@ int solveKnapsackRecursive(int capacity, int[] weights, int[] profits, int numOf
if (weights[numOfItems - 1] > capacity) {
// Store the value of function call stack in table
dpTable[numOfItems][capacity] = solveKnapsackRecursive(capacity, weights, profits, numOfItems - 1, dpTable);
return dpTable[numOfItems][capacity];
} else {
// case 1. include the item, if it is less than the capacity
final int includeCurrentItem = profits[numOfItems - 1] + solveKnapsackRecursive(capacity - weights[numOfItems - 1], weights, profits, numOfItems - 1, dpTable);
Expand All @@ -48,7 +47,7 @@ int solveKnapsackRecursive(int capacity, int[] weights, int[] profits, int numOf

// Store the value of function call stack in table and return
dpTable[numOfItems][capacity] = Math.max(includeCurrentItem, excludeCurrentItem);
return dpTable[numOfItems][capacity];
}
return dpTable[numOfItems][capacity];
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -31,4 +31,19 @@ void test3() {
int capacity = 50;
assertEquals(220, knapsackMemoization.knapSack(capacity, weight, value, weight.length));
}

@Test
void test4() {
int[] weight = {1, 2, 3};
int[] value = {10, 20, 30};
int capacity = 0;
assertEquals(0, knapsackMemoization.knapSack(capacity, weight, value, weight.length));
}
@Test
void test5() {
int[] weight = {1, 2, 3, 8};
int[] value = {10, 20, 30, 40};
int capacity = 50;
assertEquals(100, knapsackMemoization.knapSack(capacity, weight, value, weight.length));
}
}