Skip to content

Commit 5d98f5c

Browse files
Create UnboundedKnapsack.java
1 parent 92ce599 commit 5d98f5c

1 file changed

Lines changed: 29 additions & 0 deletions

File tree

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
public class UnboundedKnapsack {
2+
public static int unboundedKnapsack(int n, int w, int[] profit, int[] weight) {
3+
4+
int[][] dp = new int[n][w+1];
5+
6+
for(int i = 0; i<n; i++){ //base case
7+
dp[i][0] = 0;
8+
}
9+
10+
for(int j = 0; j<w+1; j++){ //base case
11+
dp[0][j] = (j/weight[0])*profit[0]; //profit[i] to find value each item will contribute
12+
}
13+
14+
for(int i = 1; i<n; i++){
15+
for(int j = 1; j<w+1; j++){
16+
if(j>=weight[i]){
17+
int notPick = dp[i-1][j];
18+
int pick = profit[i]+dp[i][j-weight[i]];
19+
dp[i][j] = Math.max(notPick, pick);
20+
}
21+
else{
22+
dp[i][j] = dp[i-1][j];
23+
}
24+
}
25+
}
26+
27+
return dp[n-1][w];
28+
}
29+
}

0 commit comments

Comments
 (0)