Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
afnan47
GitHub Repository: afnan47/sem7
Path: blob/main/DAA/4_0-1_Knapsack.cpp
418 views
1
#include<iostream>
2
3
using namespace std;
4
5
int main(){
6
int capacity = 10;
7
int items = 4;
8
int price[items + 1] = {0, 3, 7, 2, 9};
9
int wt[items + 1] = {0, 2, 2, 4, 5};
10
int dp[items + 1][capacity + 1];
11
12
for(int i = 0; i <= items; i++){
13
for(int j = 0; j <= capacity; j++){
14
if(i == 0 || j == 0){
15
//There's nothing to add to Knapsack
16
dp[i][j] = 0;
17
}
18
else if(wt[i] <= j){
19
//Choose previously maximum or value of current item + value of remaining weight
20
dp[i][j] = max(dp[i - 1][j], price[i] + dp[i - 1][j - wt[i]]);
21
}
22
else{
23
//Add previously added item to knapsack
24
dp[i][j] = dp[i - 1][j];
25
}
26
}
27
}
28
29
30
cout << "Maximum Profit Earned: " << dp[items][capacity] << "\n";
31
return 0;
32
}
33
34
/*
35
0/1 Knapsack :
36
Time Complexity: O(N*W).
37
where ‘N’ is the number of weight element and ‘W’ is capacity. As for every weight element we traverse through all weight capacities 1<=w<=W.
38
Auxiliary Space: O(N*W).
39
The use of 2-D array of size ‘N*W’.
40
*/
41