diff --git a/solutions/c/knapsack/1/knapsack.c b/solutions/c/knapsack/1/knapsack.c new file mode 100644 index 0000000..cccea3c --- /dev/null +++ b/solutions/c/knapsack/1/knapsack.c @@ -0,0 +1,34 @@ +#include "knapsack.h" +#include +#include +#include +#include + +// typedef struct { +// unsigned int weight; +// unsigned int value; +// } item_t; + +#define MAX(a, b) ((a) > (b) ? (a) : (b)) + +unsigned int maximum_value(unsigned int max_weight, item_t *items, size_t item_count) { + if (item_count == 0 || max_weight == 0) { + return 0; + } + + unsigned int *sack = calloc(max_weight + 1, sizeof(*sack)); + assert(sack); + + for (size_t i = 0; i < item_count; i++) { + unsigned int weight = items[i].weight; + unsigned int value = items[i].value; + + for (unsigned int w = max_weight; w >= weight; w--) { + sack[w] = MAX(sack[w], sack[w - weight] + value); + } + } + + unsigned int result = sack[max_weight]; + free(sack); + return result; +} diff --git a/solutions/c/knapsack/1/knapsack.h b/solutions/c/knapsack/1/knapsack.h new file mode 100644 index 0000000..aaebe16 --- /dev/null +++ b/solutions/c/knapsack/1/knapsack.h @@ -0,0 +1,13 @@ +#ifndef KNAPSACK_H +#define KNAPSACK_H + +#include + +typedef struct { + unsigned int weight; + unsigned int value; +} item_t; + +unsigned int maximum_value(unsigned int max_weight, item_t *items, size_t item_count); + +#endif