forked from learning-zone/java-basics
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathknapsack01.java
More file actions
32 lines (25 loc) · 868 Bytes
/
knapsack01.java
File metadata and controls
32 lines (25 loc) · 868 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
package DynamicProgramming;
public class knapsack01 {
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] values = { 10, 40, 30, 50 };
int[] weight = { 5, 4, 6, 3 };
int W = 10;
int[] values2 = { 60, 100, 120 };
int[] weight2 = { 10, 20, 30 };
int w2 = 50;
System.out.println(getMaxValue(values, weight, 0, W, 0));
System.out.println(getMaxValue(values2, weight2, 0, w2, 0));
}
public static int getMaxValue(int[] values, int[] weight, int index, int w, int val) {
// TODO Auto-generated method stub
if (index == values.length)
return val;
if (w - weight[index] >= 0) {
return Math.max(getMaxValue(values, weight, index + 1, w - weight[index], val + values[index]),
getMaxValue(values, weight, index + 1, w, val));
} else {
return getMaxValue(values, weight, index + 1, w, val);
}
}
}