Skip to content

Commit bc7f9aa

Browse files
committed
add unbounded knapsack
1 parent 3f90b1a commit bc7f9aa

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

UnboundedKnapsack.java

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
/**
2+
Problem: https://en.wikipedia.org/wiki/Knapsack_problem#Unbounded_knapsack_problem
3+
*/
4+
public class UnboundedKnapsack {
5+
public static void main(String[] args) {
6+
int C = 17;
7+
int[] wt = {4, 3, 5, 7, 11};
8+
int[] val = {5, 3, 6, 2, 7};
9+
int N = wt.length;
10+
System.out.println("Max Profit: " + unboundedKnapsack(C, N, wt, val));
11+
}
12+
13+
/**
14+
*
15+
* @param C: total weight
16+
* @param N: N items
17+
* @param wt: weights
18+
* @param val: values
19+
* @return: maximum value of items whose weight does not exceed C
20+
*/
21+
public static int unboundedKnapsack(int C, int N, int[] wt, int[] val){
22+
23+
// dp[i]: the current "best "solution" (max value) for cap. of i
24+
int[] dp = new int[C + 1];
25+
26+
for (int i = 0; i <= C; i ++){
27+
for (int j = 0; j < N; j ++){
28+
if(i >= wt[j]){
29+
dp[i] = Math.max(dp[i], val[j] + dp[i - wt[j]]);
30+
}
31+
}
32+
}
33+
return dp[C];
34+
}
35+
}

0 commit comments

Comments
 (0)