NTU SC2001 Example Class Project
We have a knapsack of capacity weight
Each object of the ith type has weight
There are unlimited supplies of each type of objects.
Find the largest total profit of any set of the objects that fits in the knapsack.
Let
0 | 1 | 2 | |
---|---|---|---|
4 | 6 | 8 | |
7 | 6 | 9 |
(3) Give a dynamic programming algorithm to compute the maximum profit, given a knapsack of capacity $C$ , $n$ types of objects with weights $W_i$ and profits $P_i$ using the bottom up approach.
The algorithm:
Since we have unlimited objects for use, a simple
Each element in the array, namely dp[i]
represents the maximum profit which can be stored in a knapsack of capacity i.
Following the recursive formula, we can construct the botton-up algorithm as following:
dp[] = int[capacity+1];
for(every object i < n){
for(every capacity j < C){
if w[i] <= j
dp[j] = max(dp[j], p[i] + dp[j - W[i]])
}
}
return dp[capacity]
Time complexity:
Space complexity:
0 | 1 | 2 | |
---|---|---|---|
5 | 6 | 8 | |
7 | 6 | 9 |