Skip to content

Commit 9e21b9e

Browse files
committed
Added Java Solution
1 parent ffad1cf commit 9e21b9e

File tree

1 file changed

+65
-0
lines changed

1 file changed

+65
-0
lines changed
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
/**
2+
@author Farheen Bano
3+
4+
Reference-
5+
https://www.geeksforgeeks.org/unbounded-knapsack-repetition-items-allowed/
6+
*/
7+
8+
//------------------------------------------------------------------------------
9+
//Memoization Approach
10+
11+
class Solution
12+
{
13+
public:
14+
int dp[1001][1001];
15+
//Function to return max value that can be put in knapsack of capacity W.
16+
int knapSack(int N, int W, int val[], int wt[]) {
17+
memset(dp,-1,sizeof(dp));
18+
KS(W,wt,val,N);
19+
}
20+
21+
//Recursive Function
22+
int KS(int W, int wt[], int val[], int N){
23+
if(N==0 || W==0)
24+
return 0;
25+
26+
if(dp[N][W]!=-1){
27+
return dp[N][W];
28+
}
29+
30+
if(wt[N-1]<=W){
31+
dp[N][W]=max(
32+
(val[N-1]+KS(W-wt[N-1],wt,val,N)),
33+
KS(W,wt,val,N-1)
34+
);
35+
return dp[N][W];
36+
}
37+
dp[N][W]=KS(W,wt,val,N-1);
38+
return dp[N][W];
39+
}
40+
};
41+
42+
//------------------------------------------------------------------------------
43+
//Tabulation Approach
44+
45+
class Solution
46+
{
47+
public:
48+
int knapSack(int N, int W, int val[], int wt[]) {
49+
int dp[N+1][W+1];
50+
51+
for(int i=0;i<N+1;i++){
52+
for(int j=0;j<W+1;j++){
53+
if(i==0||j==0){
54+
dp[i][j]=0;
55+
}
56+
else if(wt[i-1]<=j){
57+
dp[i][j]=max(val[i-1]+dp[i][j-wt[i-1]],dp[i-1][j]);
58+
}
59+
else
60+
dp[i][j]=dp[i-1][j];
61+
}
62+
}
63+
return dp[N][W];
64+
}
65+
};

0 commit comments

Comments
 (0)