From 35b87da223c41515b6ab30506980e2ba16b5f8b2 Mon Sep 17 00:00:00 2001 From: Anand <71023799+Aanandgupta@users.noreply.github.com> Date: Sat, 30 Oct 2021 12:51:13 +0530 Subject: [PATCH 1/2] Added 01 KnapSack --- 5. 0-1 Knapsack.cpp | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 5. 0-1 Knapsack.cpp diff --git a/5. 0-1 Knapsack.cpp b/5. 0-1 Knapsack.cpp new file mode 100644 index 0000000..e13d70f --- /dev/null +++ b/5. 0-1 Knapsack.cpp @@ -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> dp(n+1, vector (W+1,0)); + + for(int i=1; i= 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]; + } +}; \ No newline at end of file From 88fad32e28b9795eee6d3116e5688a75d10d0460 Mon Sep 17 00:00:00 2001 From: Anand <71023799+Aanandgupta@users.noreply.github.com> Date: Sat, 30 Oct 2021 12:52:38 +0530 Subject: [PATCH 2/2] Added Unbounded Knapsack --- 6. Unbounded Knapsack.cpp | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 6. Unbounded Knapsack.cpp diff --git a/6. Unbounded Knapsack.cpp b/6. Unbounded Knapsack.cpp new file mode 100644 index 0000000..7b33ac5 --- /dev/null +++ b/6. Unbounded Knapsack.cpp @@ -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= 0) { + dp[i] = max(dp[i], dp[i - wt[j]] + val[j]); + } + } + } + + return dp[W]; + } +}; \ No newline at end of file