data-structures · intermediate · ~15 min

0/1 Knapsack

Maximize value of items that fit a capacity, each used at most once.

Challenge

Implement:

int knapsack(const int *w, const int *v, int n, int cap);

Return the maximum total value of a subset of the n items (weights w, values v) whose total weight is <= cap. Each item is used at most once.

Input format

Weights, values, count, capacity.

Output format

Maximum achievable value.

Constraints

Iterate capacity downward for the 0/1 (once-each) constraint.

Starter code

#include <stddef.h>
/* 0/1 knapsack: max total value of items (weights w, values v, n items) fitting capacity cap. cap>=0, weights/values >=0. */
int knapsack(const int *w,const int *v,int n,int cap){ (void)w;(void)v;(void)n;(void)cap; return 0; }

Common mistakes

Iterating capacity upward turns it into unbounded knapsack (items reused).

Edge cases to handle

cap 0 -> value 0; items heavier than cap are skipped.

Background lessons

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.