Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Time Complexity for Knapsack Dynamic Programming solution

I saw the recursive dynamic programming solution to 0-1 Knapsack problem here. I memoized the solution and came up with the following code.

private static int knapsack(int i, int W, Map<Pair<Integer, Integer>>, Integer> cache)
{
 if (i < 0) {
    return 0;
 }
Pair<Integer, Integer> pair = new Pair<>(i,W);
if (cache.contains(pair)) {
  return cache.get(pair)
}
int result = -1;
if (weights[i] > W) {
    result = knapsack(i-1, W);
} else {
    result = Math.max(knapsack(i-1, W), knapsack(i-1, W - weights[i]) + values[i]);
}
cache.put(pair, result);
return result;
}

Can someone explain to me why should the time complexity be O(nW) where n is the number of items and W is the restriction on weight.

like image 772
Lee Avatar asked May 29 '26 21:05

Lee


1 Answers

It's more obvious if you think through what the table would look like in a tabular implementation of the DP. It has items on one axis and max achievable weight on the other, with one row per possible integer weight. For some weight sets, the table must be densely filled to find the optimum answer. These same weight sets will require Omega(nW) pairs in your memo hash, ergo since each entry is a constant time computation, the same time to compute all. It's a good exercise to think through how to get the costly weight sets, so I'll let that to you.

like image 156
Gene Avatar answered May 31 '26 12:05

Gene



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!