From 761612b37538a738de8950311f967c83e556400a Mon Sep 17 00:00:00 2001 From: "exercism-solutions-syncer[bot]" <211797793+exercism-solutions-syncer[bot]@users.noreply.github.com> Date: Mon, 19 Jan 2026 09:46:05 +0000 Subject: [PATCH] [Sync Iteration] c/knapsack/1 --- solutions/c/knapsack/1/knapsack.c | 34 +++++++++++++++++++++++++++++++ solutions/c/knapsack/1/knapsack.h | 13 ++++++++++++ 2 files changed, 47 insertions(+) create mode 100644 solutions/c/knapsack/1/knapsack.c create mode 100644 solutions/c/knapsack/1/knapsack.h 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