150 XP

104. Knapsack

Expert dynamic programming

You have a bag that can carry a total weight of capacity, and a list of items, each a pair [weight, value]. Write a function best_value(items, capacity) that returns the largest total value of items you can carry:

  • Each item can be taken once or not at all.
  • The total weight of the items taken must not go over capacity; exactly capacity is fine.
  • Taking nothing is allowed, so the answer is never below 0.

Taking the items with the most value per unit of weight first seems sensible but can go wrong: with a capacity of 50 and items [10, 60], [20, 100] and [30, 120], it takes the first two (160) while the last two give 220. Trying every choice of items takes 2^n tries. Work out the best value for every smaller capacity instead, one item at a time.

Example 1

Inputitems = [[1, 1], [3, 4], [4, 5], [5, 7]], capacity = 7
Output9
ExplanationWeights 3 and 4 carry 4 + 5 = 9.

Example 2

Inputitems = [[2, 3], [2, 3], [3, 5]], capacity = 4
Output6
ExplanationTwo items of weight 2 beat the one of 3.

Example 3

Inputitems = [[5, 10]], capacity = 4
Output0
ExplanationToo heavy: the bag stays empty.

Constraints

  • items has 0 to 30 pairs, each weight a whole number from 1 to 1000 and each value from 0 to 10^6.
  • capacity is a whole number from 0 to 2000.

Submit also runs 10 more tests you can't see.

Code
def best_value(items, capacity):
    """Find the most value that fits in the bag.

    items: list of [weight, value] pairs, each usable once
    capacity: int, the most weight the bag can carry
    Returns: int, the largest total value of items whose
        weights add up to at most capacity
    """
    # Write your code here
    pass