104. Knapsack
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; exactlycapacityis 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
items = [[1, 1], [3, 4], [4, 5], [5, 7]],
capacity = 79Example 2
items = [[2, 3], [2, 3], [3, 5]], capacity = 46Example 3
items = [[5, 10]], capacity = 40Constraints
itemshas 0 to 30 pairs, each weight a whole number from 1 to 1000 and each value from 0 to 10^6.capacityis a whole number from 0 to 2000.
Submit also runs 10 more tests you can't see.
- Think of a table: the best value using the first
iitems with a weight limit ofw. Itemiis either left out (the best without it, same limit) or taken (its value plus the best without it at limitw - weight). - One row is enough: a list
bestof lengthcapacity + 1, all 0 to start, updated once per item. - Go through the limits from the top down,
range(capacity, weight - 1, -1), sobest[w - weight]still means "without this item". Going up instead would let an item be taken twice.
Solve it without hints for 3 stars, with hints for 2, after seeing the solution for 1.
One way to solve it, once you've had a go.
Solving it after seeing the solution earns 1 star.
Your Submits show here, with their code, so you can go back to one. They stay in this browser.
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
Run your code to see how it does on the test cases, or Submit to check every test.