Skip to content

Commit 319b8be

Browse files
committed
Added Knapsack problem using DP
1 parent 4ced569 commit 319b8be

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed

Programs/KnapSack.java

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
//Program to implement 0-1 Knapsack using DYNAMIC PROGRAMMING
2+
import java.util.*;
3+
public class KnapSack
4+
{
5+
public int max(int a, int b)
6+
{
7+
return (a > b)?a:b;
8+
}
9+
10+
public int knapSack(int W, int wt[], int val[], int n)
11+
{
12+
int i, w;
13+
int[][] K = new int[n+1][W+1];
14+
for(i=0; i<=n; i++)
15+
{
16+
for(w=0; w<=W; w++)
17+
{
18+
if(i == 0 || w == 0)
19+
{
20+
K[i][w] = 0;
21+
}
22+
else if(wt[i-1] <= w)
23+
{
24+
K[i][w] = max(val[i-1] + K[i-1][w-wt[i-1]], K[i-1][w]);
25+
}
26+
else
27+
{
28+
K[i][w] = K[i-1][w];
29+
}
30+
}
31+
}
32+
return K[n][W];
33+
}
34+
35+
public static void main(String[] args)
36+
{
37+
int i, n, W;
38+
Scanner sc = new Scanner(System.in);
39+
System.out.println("Enter the number of items : ");
40+
n = sc.nextInt();
41+
System.out.println("Enter the maximum weight/capacity : ");
42+
W = sc.nextInt();
43+
int wt[] = new int[n];
44+
int val[] = new int[n];
45+
System.out.println("Enter the weights of the items : ");
46+
for(i=0; i<n; i++)
47+
{
48+
wt[i] = sc.nextInt();
49+
}
50+
System.out.println("Enter their corresponding values : ");
51+
for(i=0; i<n; i++)
52+
{
53+
val[i] = sc.nextInt();
54+
}
55+
KnapSack ob = new KnapSack();
56+
int res = ob.knapSack(W, wt, val, n);
57+
System.out.println("Total profit : "+res);
58+
}
59+
}

0 commit comments

Comments
 (0)