data-structures · intermediate · ~15 min
Maximize value of items that fit a capacity, each used at most once.
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.
Weights, values, count, capacity.
Maximum achievable value.
Iterate capacity downward for the 0/1 (once-each) constraint.
#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; }
Iterating capacity upward turns it into unbounded knapsack (items reused).
cap 0 -> value 0; items heavier than cap are skipped.
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.