Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions 5. 0-1 Knapsack.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
class Solution
{
public:
//Function to return max value that can be put in knapsack of capacity W.
int knapSack(int W, int wt[], int val[], int n)
{
vector<vector<int>> dp(n+1, vector<int> (W+1,0));

for(int i=1; i<dp.size(); i++) {
for(int j=1; j<dp[0].size(); j++) {
dp[i][j] = dp[i-1][j]; // agar isko na uthaye to

if(j >= wt[i-1]) {
dp[i][j] = max(dp[i][j], dp[i-1][j-wt[i-1]] + val[i-1]); // agar utha liya to
}
}
}

return dp[n][W];
}
};
17 changes: 17 additions & 0 deletions 6. Unbounded Knapsack.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
class Solution{
public:
int knapSack(int N, int W, int val[], int wt[])
{
int dp[W+1] = {0};

for(int i=1; i<=W; i++) {
for(int j=0; j<N; j++) {
if(i - wt[j] >= 0) {
dp[i] = max(dp[i], dp[i - wt[j]] + val[j]);
}
}
}

return dp[W];
}
};