Skip to content

Commit 2c39798

Browse files
committed
Added problem
1 parent 28a8dc8 commit 2c39798

File tree

2 files changed

+40
-0
lines changed

2 files changed

+40
-0
lines changed

0-1 Knapsack Problem/Question.txt

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Given weights and values of n items, put these items in a knapsack of capacity W to get the maximum total value in the knapsack. In other words, given two integer arrays val[0..n-1] and wt[0..n-1] which represent values and weights associated with n items respectively. Also given an integer W which represents knapsack capacity, find out the maximum value subset of val[] such that sum of the weights of this subset is smaller than or equal to W. You cannot break an item, either pick the complete item, or don’t pick it (0-1 property).
2+
3+

0-1 Knapsack Problem/Solution.txt

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
#include<stdio.h>
2+
#include<stdlib.h>
3+
4+
int max(int a, int b)
5+
{
6+
if (a>b)
7+
return a;
8+
else
9+
return b;
10+
}
11+
12+
int main()
13+
{
14+
int n, value[100], capacity, weight[100],i,j,K[100][100];
15+
printf("Input number of items:");
16+
scanf("%d",&n);
17+
printf("Enter values:");
18+
for(i=0;i<n;i++)
19+
scanf("%d",&value[i]);
20+
printf("Enter weights:");
21+
for(i=0;i<n;i++)
22+
scanf("%d",&weight[i]);
23+
printf("Enter Capacity:");
24+
scanf("%d",&capacity);
25+
for(i=0;i<=n;i++)
26+
for(j=0;j<=capacity;j++)
27+
{
28+
if(i==0 || j==0)
29+
K[i][j]=0;
30+
else if (weight[i-1]<=j)
31+
K[i][j]=max(K[i-1][j],K[i-1][j-weight[i-1]]+value[i-1]);
32+
else
33+
K[i][j]=K[i-1][j];
34+
}
35+
printf("%d",K[n][capacity]);
36+
return 0;
37+
}

0 commit comments

Comments
 (0)