forked from Manish1Gupta/Coding-Community-Contributions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0-1 Knapsack.cpp
More file actions
36 lines (23 loc) · 750 Bytes
/
0-1 Knapsack.cpp
File metadata and controls
36 lines (23 loc) · 750 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
class Solution
{
public:
int maxProfit(int wt[],int val[],int cap,int n,int curr,unordered_map<string,int>&mp)
{
if(curr>=n)
return 0;
string curr_key = to_string(curr) + "_" + to_string(cap);
if(mp.find(curr_key)!=mp.end())
return mp[curr_key];
int consider=0;
if(wt[curr]<=cap)
consider= val[curr] + maxProfit(wt,val,cap-wt[curr],n,curr+1,mp);
int dontconsider = maxProfit(wt,val,cap,n,curr+1,mp);
mp[curr_key]= max(consider,dontconsider);
return mp[curr_key];
}
int knapSack(int W, int wt[], int val[], int n)
{
unordered_map<string,int>mp;
return maxProfit(wt,val,W,n,0,mp);
}
};