-
Notifications
You must be signed in to change notification settings - Fork 3
/
Knapsack.java
50 lines (44 loc) · 934 Bytes
/
Knapsack.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
40
41
42
43
44
45
46
47
48
49
50
package com.geek;
import java.util.Scanner;
class Knapsack
{
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc =new Scanner(System.in);
int t=sc.nextInt();
for(int i=0;i<t;i++)
{
int n=sc.nextInt();
int W=sc.nextInt();
int wt[]=new int[n];
int v[]=new int[n];
for(int j=0;j<n;j++)
{
v[j]=sc.nextInt();
}
for(int j=0;j<n;j++)
{
wt[j]=sc.nextInt();
}
System.out.println(getKnapsack(n,W,wt,v)) ;
}
}
private static int getKnapsack(int n, int w, int[] wt, int[] v) {
// TODO Auto-generated method stub
int k[][]=new int[n+1][w+1];
for(int i=0;i<=n;i++)
{
for(int j=0;j<=w;j++)
{
if(i==0||j==0)
k[i][j]=0;
else
if(wt[i-1]<=j)
k[i][j]=Math.max(v[i-1]+k[i-1][j-(wt[i-1])], k[i-1][j]);
else
k[i][j]=k[i-1][j];
}
}
return k[n][w];
}
}