Here is an O(nW) time algorithm for the generalized knapsack problem:
1. Create a 2D array dp of size (n+1) x (W+1). dp[i][w] will store the maximum value that can be achieved with weight <= w using objects up to i.
2. Initialize dp[0][w] = 0 for all w, as no objects are considered yet.
3. For each object i:
- For each weight w from 0 to W:
- If the weight of object i (wi) is <= w, dp[i][w] = max(dp[i-1][w], dp[i-1][w-wi] + vi)
- Else, dp[i][w] = dp[i-1][w]
4. Return dp[n][W]
This implements a bottom-up dynamic programming approach. We consider each object and fill in the dp table by either not picking the object (dp[i-1][w]) or picking it if it fits (dp[i-1][w-wi] + vi).
Correctness: The dp array stores the optimal solutions for all prefix sets of objects and all possible weight capacities. By building it up from empty to full object sets, we iteratively find the best solutions.
Time complexity:
- There are n objects and W possible weights, so the 2D array is of size n*W.
- Each entry takes O(1) work to compute.
- Therefore, the overall time complexity is O(n*W).
So this solves the generalized knapsack problem in O(nW) time.