The problem
Each item is (weight, value), with whole-number weights. Choose items whose weights add up to at most cap and whose values add up to as much as possible. Each item can be taken at most once. Return the positions of the chosen items in items, as a list in any order.
pack([(3, 4), (4, 5), (2, 3)], 7) # [0, 1]
# weight 3 + 4 = 7, value 4 + 5 = 9
pack([(5, 10)], 4) # []
When several choices have the best value, any of them is accepted. The tests check the facts of your answer: every position is valid and used once, the weight fits, and the total value is the best possible.
Limits
- Up to 200 items, with weights from 1 to 100 and
capup to 3,000. Trying every choice (2²⁰⁰ of them, 200 twos multiplied together) is impossible.
Builds on DYNP-8 The knapsack family and DYNP-9 Rebuilding the answer.
Continue on a laptop
Practice runs Python in the browser and needs a keyboard and a wider screen. Read the problem and open hints here, then write your solution on a laptop. Progress is saved per browser for now, so hints opened here stay on this device.
Need a hint?0 of 3 opened
- Hint 1Nudge
- Hint 2Approach Open hint 1 first
- Hint 3Pseudocode Open hint 2 first
- Worked solutionlast resort Opens after all 3 hints
Ctrl + Enter runs the tests. Tab indents; press Esc, then Tab, to leave the editor.
| # | Test | Result | Reads · time |
|---|---|---|---|
| 1 | The example | Not run | |
| 2 | Nothing fits | Not run | |
| 3 | No items | Not run | |
| 4 | Everything fits | Not run | |
| 5 | Greedy fails | Not run | |
| 6 | Equal weights | Not run | |
| 7 | Each item once | Not run | |
| 8 | 100 items, bag of 2,500 | Not run | |
| 9 | 200 items, bag of 3,000 | Not run |