-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathMain.java
39 lines (34 loc) · 1.01 KB
/
Main.java
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
import java.util.Scanner;
public class Main {
private static Scanner sc = new Scanner(System.in);
private static int N;
private static int K;
private static Bag[] bags;
private static int[] knapsack;
public static void main(String[] args) {
N = sc.nextInt();
K = sc.nextInt();
bags = new Bag[N];
knapsack = new int[K + 1];
for(int i = 0; i < N; i ++){
bags[i] = new Bag(sc.nextInt(), sc.nextInt());
}
for (int i = 0; i < N; i++) {
for(int j = K; j >= 0; j --){
if(bags[i].weight <= j) {
knapsack[j] = Math.max(knapsack[j],
knapsack[j - bags[i].weight] + bags[i].value);
}
}
}
System.out.println(knapsack[K]);
}
static class Bag{
private int value;
private int weight;
public Bag(int weight, int value) {
this.value = value;
this.weight = weight;
}
}
}