Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Enquire Book a call

Coding · Dynamic programming

The 0/1 knapsack

Medium · Target 20 minutes · Dynamic programming · Type asked atAmazonGoogle

There are n items; item i weighs weights[i] and is worth values[i]. Choose a set of items, each at most once, whose total weight is at most capacity, and return the largest total value possible.

Examples

InputOutputWhy
weights = [1,3,4,5], values = [1,4,5,7], capacity = 79The 3 and the 4: weight 7, value 9.
weights = [5,4,6,3], values = [10,40,30,50], capacity = 1090Weights 4 and 3: value 90.
weights = [10], values = [5], capacity = 90Nothing fits.

Constraints

  • 1 ≤ n ≤ 100
  • 1 ≤ weights[i] ≤ 1000
  • 1 ≤ values[i] ≤ 10⁴
  • 0 ≤ capacity ≤ 10⁴

Hints

Hint 1

Decide item by item. After the first i items, only the remaining capacity matters.

Hint 2

best[i][c] = max(best[i − 1][c], values[i] + best[i − 1][c − weights[i]]).

Hint 3

With one array, loop the capacity downwards so that best[c − w] still refers to the previous item.

Where people lose marks

  • Looping capacities upwards with one array, which reuses items (that is the unbounded knapsack).
  • Greedy by value per unit weight, which fails on the first example.
  • Returning best[capacity] from a table initialised to −∞ instead of 0 for "exactly full".
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.