-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKnapsack_01.java
More file actions
73 lines (56 loc) · 1.76 KB
/
Knapsack_01.java
File metadata and controls
73 lines (56 loc) · 1.76 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
63
64
65
66
67
68
69
70
71
72
73
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Knapsack_01 {
static int knapsack_01(int []wt, int []val, int n,int total_weight)
{
int a[][] = new int[n+1][total_weight+1];
for(int i=0; i <= n; i++)
{
for(int j=0; j <=total_weight; j++)
{
if(i == 0 || j == 0)
{
a[i][j] = 0;
System.out.print(a[i][j] + " ");
continue;
}
if(wt[i] > j)
a[i][j] = a[i-1][j];
else
a[i][j] = Math.max( (val[i] + a[i-1][j-wt[i]]) , a[i-1][j]);
System.out.print(a[i][j] + " ");
}
System.out.println();
}
return a[n][total_weight];
}
public static void main(String[] args)
{
/*
*
Scanner in = new Scanner(System.in);
System.out.println("Enter Total weight");
int total_weight = in.nextInt();
System.out.println("Enter np of items");
int no_of_items = in.nextInt();
int wt[] = new int[no_of_items+1];
int val[] = new int[no_of_items+1];
System.out.println("weights == >");
for(int i=1; i < no_of_items+1; i++)
wt[i] = in.nextInt();
System.out.println("values ==>");
for(int i=1; i < no_of_items+1; i++)
val[i] = in.nextInt();
*
*/
int total_weight = 7;
int no_of_items = 4;
int wt[] = {0,1,3,4,5};
int val[] = {0,1,4,5,7};
int max_val = knapsack_01(wt, val,no_of_items,total_weight);
System.out.println(max_val);
}
}