-
Notifications
You must be signed in to change notification settings - Fork 81
/
Copy path0 1 Knapsack Problem
62 lines (53 loc) · 1.29 KB
/
0 1 Knapsack Problem
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
/*
A thief robbing a store can carry a maximal weight of W into his knapsack. There are N items, and i-th item weigh 'Wi' and the value being 'Vi.'
What would be the maximum value V, that the thief can steal?
Input Format :
The first line of the input contains an integer value N, which denotes the total number of items.
The second line of input contains the N number of weights separated by a single space.
The third line of input contains the N number of values separated by a single space.
The fourth line of the input contains an integer value W, which denotes the maximum weight the thief can steal.
Output Format :
Print the maximum value of V that the thief can steal.
Constraints :
1 <= N <= 20
1<= Wi <= 100
1 <= Vi <= 100
Time Limit: 1 sec
Sample Input 1 :
4
1 2 4 5
5 4 8 6
5
Sample Output 1 :
13
Sample Input 2 :
5
12 7 11 8 9
24 13 23 15 16
26
Sample Output 2 :
51
*/
public class Solution {
public static int knapsack(int[] wt, int[] val, int n, int W) {
//Your code goes here
int[][] dp = new int[n+1][W+1];
for (int i=n-1;i>=0;i--)
{
for (int w=0;w<=W;w++)
{
if (wt[i]<=w)
{
int ans1=dp[i+1][w];
int ans2=dp[i+1][w-wt[i]] + val[i];
dp[i][w]=Math.max(ans1, ans2);
}
else
{
dp[i][w]=dp[i+1][w];
}
}
}
return dp[0][W];
}
}