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

Medium · Target 20 minutes · Dynamic programming

Item i weighs weights[i], is worth values[i], and has counts[i] identical copies. Choose how many copies of each to take (between 0 and its count) so that the total weight is at most capacity, and return the largest total value.

Examples

InputOutputWhy
weights = [2,3], values = [3,4], counts = [2,1], capacity = 710Both copies of the first item and the second item: weight 7.
weights = [1,2,3], values = [10,15,40], counts = [2,1,1], capacity = 665Weights 1 + 2 + 3: values 10 + 15 + 40.
weights = [4], values = [5], counts = [3], capacity = 910Only two copies fit.

Constraints

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

Hints

Hint 1

Treating every copy as a separate 0/1 item works but costs O(capacity · Σ counts).

Hint 2

Any number from 0 to k is a sum of distinct bundles 1, 2, 4, …, 2ᵖ and a remainder.

Hint 3

Turn each item into those bundles and run the 0/1 knapsack, capacities downwards, over the bundles.

Where people lose marks

  • Bundles that overshoot the count (1, 2, 4, 8 for a count of 13 allows 15 copies): the last bundle must be the remainder.
  • Looping capacities upwards, which lets a bundle be taken twice.
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.