DYNP-P9

Which items to pack

Practice 9 of 9Dynamic programming9 tests

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 cap up 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

  1. Hint 1Nudge
  2. Hint 2Approach Open hint 1 first
  3. Hint 3Pseudocode Open hint 2 first
  4. Worked solutionlast resort Opens after all 3 hints
Python waits for a wider screensolution.py

Ctrl + Enter runs the tests. Tab indents; press Esc, then Tab, to leave the editor.

9 tests, not run yet
Test results
#TestResultReads · time
1The exampleNot run
2Nothing fitsNot run
3No itemsNot run
4Everything fitsNot run
5Greedy failsNot run
6Equal weightsNot run
7Each item onceNot run
8100 items, bag of 2,500Not run
9200 items, bag of 3,000Not run