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 unbounded knapsack

Medium · Target 15 minutes · Dynamic programming

There are n item types; type i weighs weights[i] and is worth values[i], and you may take any number of each. Return the largest total value whose total weight is at most capacity.

Examples

InputOutputWhy
weights = [2,3,5], values = [3,5,9], capacity = 9155 + 2 + 2, or 3 + 3 + 3.
weights = [1,3,4], values = [15,50,60], capacity = 81303 + 3 + 1 + 1: 50 + 50 + 15 + 15. Eight of the first item would give only 120.
weights = [3], values = [5], capacity = 20Nothing fits.

Constraints

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

Hints

Hint 1

With unlimited copies the item index does not need to be in the state: best[c] = max over items of values[i] + best[c − weights[i]].

Hint 2

Equivalently, run the 0/1 loop with capacities going upwards, so best[c − w] may already include the same item.

Where people lose marks

  • Looping downwards, which allows each item only once.
  • Assuming the bag must be filled exactly: here it may be left partly empty.
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.