-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0-1knapsack.c
More file actions
33 lines (27 loc) · 791 Bytes
/
0-1knapsack.c
File metadata and controls
33 lines (27 loc) · 791 Bytes
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
#include <stdio.h>
#include <stdlib.h>
#define MAX(a, b) ((a) > (b) ? (a) : (b))
int knapSack(int W, int wt[], int val[], int n)
{
int **dp = (int **) malloc((n + 1) * sizeof(int *));
for (int i = 0; i <= n; i++) {
dp[i] = (int *) malloc((W + 1) * sizeof(int));
}
for (int i = 0; i <= n; i++) {
for (int w = 0; w <= W; w++) {
if (i == 0 || w == 0) {
dp[i][w] = 0;
} else if (wt[i-1] <= w) {
dp[i][w] = MAX(val[i-1] + dp[i-1][w-wt[i-1]], dp[i-1][w]);
} else {
dp[i][w] = dp[i-1][w];
}
}
}
int result = dp[n][W];
for (int i = 0; i <= n; i++) {
free(dp[i]);
}
free(dp);
return result;
}