-
Notifications
You must be signed in to change notification settings - Fork 4
/
Knapsack1.java
72 lines (64 loc) · 1.27 KB
/
Knapsack1.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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import java.util.*;
class Knapsack1
{
public static void KnapSack(int [] v,int[] w,int n,int W)
{
int c[][]=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)
{
c[i][j]=0;
}
else if(w[i-1]<=j)
{
if(v[i-1]+c[i-1][j-w[i-1]]>c[i-1][j])
{
c[i][j]=v[i-1]+c[i-1][j-w[i-1]];
}
else
{
c[i][j]=c[i-1][j];
}
}
else
{
c[i][j]=c[i-1][j];
}
}
}
for(int i=0;i<=n;i++)
{
for(int j=0;j<=W;j++)
{
System.out.print(c[i][j]+"\t");
}
System.out.println();
}
System.out.println();
System.out.println("The max value that can be put in knapsack capacity of "+W+" is "+c[n][W]);
}
public static void main(String ar[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter number of items");
int n=sc.nextInt();
System.out.println("Enter capacity of knapsack");
int W=sc.nextInt();
int v[]=new int[n];
int w[]=new int[n];
System.out.println("Enter value array");
for(int i=0;i<n;i++)
{
v[i]=sc.nextInt();
}
System.out.println("Enter weight array");
for(int i=0;i<n;i++)
{
w[i]=sc.nextInt();
}
KnapSack(v,w,n,W);
}
}