HARD-P3

The most valuable load

Practice 3 of 5Hard problems11 tests

The problem

A wagon can carry cap kilograms. Each item (weight, value) can be loaded once or not at all. Return the largest total value that fits. This is the 0/1 knapsack (DYNP-8), but with numbers far too large for a table.

best_value([(1, 2), (10, 15)], 10)            # 15
best_value([(6, 30), (5, 24), (5, 24)], 10)    # 48

Limits

  • Up to 100 items; weights and values up to about 10⁹; cap up to about 5 × 10¹⁰.
  • A table by weight or by value is far too big, and trying all 2ⁿ choices is impossible. Branch and bound with a good bound works.

Builds on HARD-3 Branch and bound.

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.

11 tests, not run yet
Test results
#TestResultReads · time
1No itemsNot run
2Nothing fitsNot run
3One itemNot run
4Best value per kilogram goes wrongNot run
5Two of the second bestNot run
6Items worth nothingNot run
7Everything fitsNot run
8Thirty itemsNot run
9100 items, values unrelated to weightsNot run
10100 items, values near the weightsNot run
1160 items, every value 10⁸ above its weightNot run