Infinite Knapsack

Knapsack problem with unlimited supply of items.

Full Knapsack

You are given a knapsack with capacity C. There are n types of free items you can choose from. Each item has a weight and a value. Your goal is to stuff the bag and maximize the total value. Assume the supply for each item is unlimited.

Example

I: weights=[2,3,5,7], values=[1,5,2,4], capacity=10
O: 5+5+5 = 15

Approach

1. Optimal Subproblem
    kp(w) = maximal value with capacity w
2. Solve by prefix
    for all items that can fit in the bag
        kp(w) = Math.max(kp(w), value(j) + kp(w-weight(j)))
3. Topo Order
    for w from 1 to capacity
4. Base case
    kp(0) = 0 no space = no value
5. Final Answer
    kp(capacity)

Code (LI.440)

Time & Space Complexity

0/1 Knapsack

What if there's only one unit for each item?

Example

First Attempt

Second Try

Note that define/solve by suffix is also fine

Code (LI.125)

Pseudo-Polynomial Time

We successfully tried all possible subsets. What's the runtime then? #subproblem = O(n*capacity) and time/subproblem = O(1) so the total running time is O(n*capacity). Note that polynomial time means polynomial in n. But capacity is not. With a worst case of exponential time in n, this algorithm runs in pseudo-polynomial time.

Space Complexity

Right now, we are using a two dimensional array to store all the states. So the space complexity is O(n*capacity). There are two ways to optimize space. We can still define the subproblem the same way and realize that we only need 2 dependencies so we can compress the rows to 2. Or we can define the subproblems like how we did in the full knapsack problem, using just the weights. Either way, we will lose the ability to recover the subset of items (using parent pointer).

Space Optimization

Last updated