From 8b3fdd4954d682c0539963642fda1e7b4b48152e Mon Sep 17 00:00:00 2001 From: Pratham Raj <146612404+GeekyPratham@users.noreply.github.com> Date: Mon, 28 Oct 2024 17:57:22 +0530 Subject: [PATCH] Create unbounded_knapsack.cpp I am adding all the approaches for solving this problem like top - down and bottom up and it more space optimization. --- dynamic_programming/unbounded_knapsack.cpp | 117 +++++++++++++++++++++ 1 file changed, 117 insertions(+) create mode 100644 dynamic_programming/unbounded_knapsack.cpp diff --git a/dynamic_programming/unbounded_knapsack.cpp b/dynamic_programming/unbounded_knapsack.cpp new file mode 100644 index 00000000000..20639a4e24a --- /dev/null +++ b/dynamic_programming/unbounded_knapsack.cpp @@ -0,0 +1,117 @@ +include +using namespace std; + + +// top down approach -> recursion + memoization +class Solution{ +public: + int calculateMaximumProfit(int n,int w,int val[],int wt[],int idx,vector >& dp){ + // base case + if (idx == 0) { + if (wt[0] <= w) return val[0] * (w / wt[0]); + return 0; + + } + + if(dp[idx][w]!=-1) return dp[idx][w]; // if the dp is already calculate then no need for further go + + // if a person not intereseted to pick + int notpick = 0 + calculateMaximumProfit(n,w,val,wt,idx-1,dp); + int pick = INT_MIN; + // person can pick only when if the weight of index is less or equal to the knapsack weight; + if(wt[idx]<=w){ + pick = val[idx] + calculateMaximumProfit(n,w-wt[idx],val,wt,idx,dp); + } + + return dp[idx][w] = max(pick,notpick); + + } + int knapSack(int n, int w, int val[], int wt[]) + { + + vector > dp(n,vector (w+1,-1)); + return calculateMaximumProfit(n,w,val,wt,n-1,dp); + } +}; +// T.C = O(n*w); +// S.C = O(n*w) + O(n); for dp (n*w) and auxiliary stack space i.e due to recursion O(n); + + +// bottom up approach + + +class Solution{ +public: + + int knapSack(int n, int w, int val[], int wt[]) + { + vector > dp(n,vector (w+1,0)); + + for(int i=0;i<=w;i++){ + dp[0][i]=(i/wt[0])*val[0]; + + } + for(int i=1;i prev(w+1,0),curr(w+1,0); + for(int i=0;i<=w;i++){ + prev[i]=(i/wt[0])*val[0]; + + } + for(int i=1;i>t; + while(t--){ + int N,W; + cin>>N>>W; + int val[N],wt[N}; + for(int i=0;i>val[i]; + for(int i=0;i>wt[i]; + + Solution ob; + cout<