0/1 Knapsack
Write the code, see it run, pass the checks.
The problem
- hard
- Code
- Pro
Write knapsack(weights, values, capacity): item i weighs weights[i] and is worth values[i], both whole numbers of at least 1, and the two arrays have the same length, possibly 0. A bag holds a total weight of at most capacity, a whole number from 0. Taking each item at most once, return the largest total value that fits. For example, knapsack([1, 3, 4, 5], [1, 4, 5, 7], 7) is 9, from the items weighing 3 and 4. The checks include 200 items and a capacity of 10,000, so trying every set of items is too slow: work out the best value for every capacity up to the limit.
Your code must pass
- Finds the most valuable load
- Beats taking the best value per weight first
- Takes each item at most once
- Handles no room and no items
- Is fast enough for 200 items and a capacity of 10,000