-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKnapsack_Problem.java
More file actions
62 lines (46 loc) · 1.11 KB
/
Knapsack_Problem.java
File metadata and controls
62 lines (46 loc) · 1.11 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
import java.util.Scanner;
public class Knapsack_Problem {
/*
* Solution to the classic 0/1 knapsack problem
*/
public static int itemCount;
public static int maxWeight;
public static int[] weight;
public static int[] value;
public static int[][] f;
public static int max(int a, int b){
if (a > b) return a;
return b;
}
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
itemCount = scan.nextInt();
maxWeight = scan.nextInt();
weight = new int[itemCount];
value = new int[itemCount];
f = new int[maxWeight][itemCount];
for (int i=0; i<itemCount; i++){
weight[i] = scan.nextInt();
value[i] = scan.nextInt();
}
scan.close();
for (int i=0; i<itemCount; i++){
for (int j=0; j<maxWeight; j++){
if (weight[i] > j){
if (i == 0){
f[j][i] = 0;
} else {
f[j][i] = f[j][i - 1];
}
} else {
if (i == 0){
f[j][i] = value[i];
} else {
f[j][i] = max(f[j][i - 1], f[j - weight[i]][i - 1] + value[i]);
}
}
}
}
System.out.println(f[maxWeight - 1][itemCount - 1]);
}
}