Skip to content

Commit ec120ae

Browse files
replsanjuveapen
authored andcommitted
Fix to knapsack solution
1 parent 61e29b0 commit ec120ae

File tree

1 file changed

+3
-6
lines changed

1 file changed

+3
-6
lines changed

src/main/java/dynamicprogramming/Knapsack01.java

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -46,11 +46,9 @@ public int recursiveDP(Item[] items, int index, int remainingweight) {
4646
}
4747

4848
public int recursiveDP(Item[] items, int index, int remainingweight, Map<Integer, Map<Integer, Integer>> cache) {
49-
5049
if (index == items.length || items[index] == null) {
5150
return 0;
5251
}
53-
5452
if (!cache.containsKey(index)) {
5553
cache.put(index, new HashMap<Integer, Integer>());
5654
}
@@ -61,13 +59,12 @@ public int recursiveDP(Item[] items, int index, int remainingweight, Map<Integer
6159

6260
int toReturn = 0;
6361
if (items[index].weight > remainingweight) {
64-
toReturn = naive(items, index + 1, remainingweight);
62+
toReturn = recursiveDP(items, index + 1, remainingweight);
6563
} else {
66-
toReturn = Math.max(naive(items, index + 1, remainingweight - items[index].weight) + items[index].value,
67-
naive(items, index + 1, remainingweight));
64+
toReturn = Math.max(recursiveDP(items, index + 1, remainingweight - items[index].weight) + items[index].value,
65+
recursiveDP(items, index + 1, remainingweight));
6866
}
6967
cacheEntry.put(remainingweight, toReturn);
7068
return toReturn;
71-
7269
}
7370
}

0 commit comments

Comments
 (0)