Practice
JavaScriptData StructuresReactConcepts
Sign in
← Back to problems

0/1 Knapsack

Dynamic Programmingmedium

Implement `knapsack(weights, values, capacity)` returning the maximum total value of items that fit, where each item can be taken at most once.

Sample tests

Input: knapsack([1,3,4,5], [1,4,5,7], 7)
Output: 9
Input: knapsack([1,2,3], [6,10,12], 5)
Output: 22

+ 1 hidden test run on Submit.

Hints

Common pitfalls
  • Iterating capacity low-to-high reuses an item (that is the unbounded variant).

Learning resources

  • Wikipedia: Dynamic programming
Approach & explanation (try first)

A 1D DP filled from high capacity down keeps each item once. O(n * capacity) time.

Loading...
⌘/Ctrl + Enter

Run your code to see results.