-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUnboundedKnapsack.java
More file actions
35 lines (27 loc) · 860 Bytes
/
Copy pathUnboundedKnapsack.java
File metadata and controls
35 lines (27 loc) · 860 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
package Arrays;
import java.util.Arrays;
/*
https://iq.opengenus.org/unbounded-knapsack-problem/
*/
public class UnboundedKnapsack {
public static void main(String[] args) {
int val[] = {10,30,20};
int weight[] = {5, 10, 15};
int Capacity = 100;
System.out.println(solution(Capacity, weight, val));
}
public static double solution(int capacity, int[] weight, int[] value) {
int[] dp = new int[capacity +1];
Arrays.fill(dp, 0);
if (weight.length == 0 || capacity == 0)
return 0;
for (var i = 0; i <= capacity; i++) {
for (var j = 0; j < weight.length; j++) {
if (weight[j] <= i) {
dp[i] = Math.max(dp[i], dp[i - weight[j]] + value[j]);
}
}
}
return dp[capacity];
}
}