Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions solutions/c/knapsack/1/knapsack.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
#include "knapsack.h"
#include <assert.h>
#include <stddef.h>
#include <stdint.h>
#include <stdlib.h>

// 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;
}
13 changes: 13 additions & 0 deletions solutions/c/knapsack/1/knapsack.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
#ifndef KNAPSACK_H
#define KNAPSACK_H

#include <stddef.h>

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