Skip to content

Commit e38611e

Browse files
authored
Optimize and Format Knapsack Memoization Algorithm (#5685)
1 parent b81671e commit e38611e

File tree

2 files changed

+20
-6
lines changed

2 files changed

+20
-6
lines changed

src/main/java/com/thealgorithms/dynamicprogramming/KnapsackMemoization.java

+5-6
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
package com.thealgorithms.dynamicprogramming;
22

3+
import java.util.Arrays;
4+
35
/**
46
* Recursive Solution for 0-1 knapsack with memoization
57
* This method is basically an extension to the recursive approach so that we
@@ -15,10 +17,8 @@ int knapSack(int capacity, int[] weights, int[] profits, int numOfItems) {
1517
int[][] dpTable = new int[numOfItems + 1][capacity + 1];
1618

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

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

4948
// Store the value of function call stack in table and return
5049
dpTable[numOfItems][capacity] = Math.max(includeCurrentItem, excludeCurrentItem);
51-
return dpTable[numOfItems][capacity];
5250
}
51+
return dpTable[numOfItems][capacity];
5352
}
5453
}

src/test/java/com/thealgorithms/dynamicprogramming/KnapsackMemoizationTest.java

+15
Original file line numberDiff line numberDiff line change
@@ -31,4 +31,19 @@ void test3() {
3131
int capacity = 50;
3232
assertEquals(220, knapsackMemoization.knapSack(capacity, weight, value, weight.length));
3333
}
34+
35+
@Test
36+
void test4() {
37+
int[] weight = {1, 2, 3};
38+
int[] value = {10, 20, 30};
39+
int capacity = 0;
40+
assertEquals(0, knapsackMemoization.knapSack(capacity, weight, value, weight.length));
41+
}
42+
@Test
43+
void test5() {
44+
int[] weight = {1, 2, 3, 8};
45+
int[] value = {10, 20, 30, 40};
46+
int capacity = 50;
47+
assertEquals(100, knapsackMemoization.knapSack(capacity, weight, value, weight.length));
48+
}
3449
}

0 commit comments

Comments
 (0)