From 6f51be6e3348fb27870cfe609325d16253d724ec Mon Sep 17 00:00:00 2001 From: coders-group11 <92266181+coders-group11@users.noreply.github.com> Date: Sun, 10 Oct 2021 21:57:50 +0530 Subject: [PATCH] Create knapsack.c --- knapsack.c | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 knapsack.c diff --git a/knapsack.c b/knapsack.c new file mode 100644 index 000000000..a3d2d2697 --- /dev/null +++ b/knapsack.c @@ -0,0 +1,31 @@ +#include +int max(int a, int b) { + if(a>b){ + return a; + } else { + return b; + } +} +int knapsack(int W, int wt[], int val[], int n) { + int i, w; + int knap[n+1][W+1]; + for (i = 0; i <= n; i++) { + for (w = 0; w <= W; w++) { + if (i==0 || w==0) + knap[i][w] = 0; + else if (wt[i-1] <= w) + knap[i][w] = max(val[i-1] + knap[i-1][w-wt[i-1]], knap[i-1][w]); + else + knap[i][w] = knap[i-1][w]; + } + } + return knap[n][W]; +} +int main() { + int val[] = {20, 25, 40}; + int wt[] = {25, 20, 30}; + int W = 50; + int n = sizeof(val)/sizeof(val[0]); + printf("The solution is : %d", knapsack(W, wt, val, n)); + return 0; +}