Skip to content

Commit

Permalink
added three new code about dp
Browse files Browse the repository at this point in the history
  • Loading branch information
Asad-Bin committed Dec 26, 2022
1 parent 2356bcc commit 362f117
Show file tree
Hide file tree
Showing 3 changed files with 63 additions and 0 deletions.
42 changes: 42 additions & 0 deletions dp/0-1-knapsack-rv.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
// time O(N*W)
// space O(N+W) for dp + O(N) for recursion stack
# include <bits/stdc++.h>
using namespace std;
const int N = 1e5;
const int maxW = 1e2;
const long long int inf = 1e15;

int weight[N+5];
long long int value[N+5];
long long int dp[N+5][maxW+5];

long long int calc(int n, int taken){
if(n == 0){
if(taken == 0) return 0;
else return -inf;
}
if(dp[n][taken] != -1) return dp[n][taken];

dp[n][taken] = calc(n-1, taken); // not taking nth item
if(taken >= weight[n]) dp[n][taken] = max(dp[n][taken], calc(n-1, taken-weight[n]) + value[n]);

return dp[n][taken];
}
int main(){
memset(dp, -1, sizeof(dp));
int n, W;
cin>>n>>W;
for(int i= 1; i<=n; i++) cin>>weight[i]>>value[i];

long long int ans = -inf;
for(int w = 0; w <= W; w++){
ans = max(ans, calc(n, w));
}

cout<<ans<<endl;
return 0;
}




17 changes: 17 additions & 0 deletions dp/0-1-knapsack.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
// time O(N*W)
// memory O(N)

int knapSack(int W, int wt[], int val[], int n)
{
// making and initializing dp array
int dp[W + 1];
memset(dp, 0, sizeof(dp));

for (int i = 1; i < n + 1; i++) {
for (int w = W; w >= 0; w--) {
if (wt[i - 1] <= w) // finding the maximum value
dp[w] = max(dp[w], dp[w - wt[i - 1]] + val[i - 1]);
}
}
return dp[W]; // returning the maximum value of knapsack
}
4 changes: 4 additions & 0 deletions dp/double-knapsack.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
For each ‘i’, we can either: 
1. Don’t select the item ‘i’.
2. Fill the item ‘i’ in first knapsack.
3. Fill the item ‘i’ in second knapsack.

0 comments on commit 362f117

Please sign in to comment.