-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKnapsackRepetitiveElements.java
More file actions
64 lines (53 loc) · 1.55 KB
/
KnapsackRepetitiveElements.java
File metadata and controls
64 lines (53 loc) · 1.55 KB
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import java.util.Arrays;
public class KnapsackRepetitiveElements {
static int[][] dp=new int[3][4];
public static int knapsackRepeat(int N, int W, int[] val, int[] wt){
if(N==0 || W==0)
return 0;
if(dp[N][W]!=-1)
return dp[N][W];
int ans=0,c1,c2;
if(wt[N-1] > W){
ans = knapsackRepeat(N-1, W, val, wt);
}
else{
c1 = val[N-1] + knapsackRepeat(N, W-wt[N-1], val, wt);
c2 = knapsackRepeat(N-1, W, val, wt);
ans = Math.max(c1, c2);
}
dp[N][W] =ans;
return dp[N][W];
}
public static void main(String args[]){
// for(int[] col:dp)
// Arrays.fill(col, -1);
int[] val = {1,1};
int[] wt = {2,1};
int w =3;
// int ans = knapsackRepeat(4, w, val, wt);
for(int i=0;i<3;i++){
for(int j=0;j<4;j++){
if(i==0||j==0){
dp[i][j] = 0;
}
}
}
for(int i=1;i<3;i++){
for(int j=1;j<4;j++){
if(wt[i-1] > j){
dp[i][j] = dp[i-1][j];
}
else{
dp[i][j] = Math.max(val[i-1] + dp[i][j-wt[i-1]], dp[i-1][j]);
}
}
}
for(int[] col: dp){
for(int row: col){
System.out.print(row+" ");
}
System.out.println();
}
// System.out.print(ans);
}
}