Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 57c3a12

Browse files
Create 0 1 Knapsack Problem
1 parent c505e96 commit 57c3a12

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
/*
2+
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.'
3+
What would be the maximum value V, that the thief can steal?
4+
5+
Input Format :
6+
The first line of the input contains an integer value N, which denotes the total number of items.
7+
The second line of input contains the N number of weights separated by a single space.
8+
The third line of input contains the N number of values separated by a single space.
9+
The fourth line of the input contains an integer value W, which denotes the maximum weight the thief can steal.
10+
11+
Output Format :
12+
Print the maximum value of V that the thief can steal.
13+
14+
Constraints :
15+
1 <= N <= 20
16+
1<= Wi <= 100
17+
1 <= Vi <= 100
18+
Time Limit: 1 sec
19+
20+
Sample Input 1 :
21+
4
22+
1 2 4 5
23+
5 4 8 6
24+
5
25+
Sample Output 1 :
26+
13
27+
28+
Sample Input 2 :
29+
5
30+
12 7 11 8 9
31+
24 13 23 15 16
32+
26
33+
Sample Output 2 :
34+
51
35+
*/
36+
37+
public class Solution {
38+
39+
public static int knapsack(int[] wt, int[] val, int n, int W) {
40+
//Your code goes here
41+
int[][] dp = new int[n+1][W+1];
42+
43+
for (int i=n-1;i>=0;i--)
44+
{
45+
for (int w=0;w<=W;w++)
46+
{
47+
if (wt[i]<=w)
48+
{
49+
int ans1=dp[i+1][w];
50+
int ans2=dp[i+1][w-wt[i]] + val[i];
51+
dp[i][w]=Math.max(ans1, ans2);
52+
}
53+
else
54+
{
55+
dp[i][w]=dp[i+1][w];
56+
}
57+
}
58+
}
59+
return dp[0][W];
60+
}
61+
62+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /