-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathknapsack.java
More file actions
62 lines (46 loc) · 894 Bytes
/
knapsack.java
File metadata and controls
62 lines (46 loc) · 894 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
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.*;
class knapsack
{
public static void main(String args[])
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter number of items ");
int n=scan.nextInt();
int weight[]=new int[n+1];
int value[]=new int[n+1];
System.out.println("Please Enter weight of an item and corresponding value of item ");
for(int j=1;j<=n;j++)
{
weight[j]=scan.nextInt();
value[j]=scan.nextInt();
}
System.out.println("Enter Macximum weight ");
int W=scan.nextInt();
int table[][]=new int[n+1][W+1];
for(int i=0;i<=n;i++)
{
for(int j=0;j<=W;j++)
{
if(j==0||i==0)
table[i][j]=0;
else
{
table[i][j]=table[i-1][j];
if(weight[i]<=j)
{
table[i][j]=Math.max(value[i]+table[i-1][j-weight[i]],table[i-1][j]);
}
}
}
}
String Ans="";
for(int i=1;i<=n;i++)
{
for(int j=1;j<=W;j++)
{
System.out.print(table[i][j]+" ");
}
System.out.println();
}
}
}