Backpack Problem¶
🎯 Optimize the value of a heist.
A burglar broke into a villa. There he finds so many valuables that he can’t put them all in his backpack. Write a program that makes an optimal selection.
The burglar is an experienced professional who can estimate the market value and size of each item in no time:
item |
size |
value |
|---|---|---|
laptop |
2 |
600,- |
cutlery |
2 |
400,- |
spotify speakers |
3 |
300,- |
jewels |
2 |
1100,- |
vase |
5 |
700,- |
camera |
2 |
500,- |
painting |
4 |
900,- |
cash |
1 |
800,- |
The backpack has a capacity of 8.
When your program manages to pack items worth 3000, it can be used
as an app for amateur burglars.
Hints¶
The optimal solution uses dynamic programming.
Use the following pseudocode:
create an empty data structure for the best combinations for each backpack size
insert an empty combination for a size 0 backpack
start with a size 1 backpack
store the best combination for the current size minus one as
current bestgo through all items
create a new combination usign an item plus the best combination for the space remaining
if the combination is more valuable than the
current best, replacecurrent bestby the new combinationif the combination is worth the same amount, save both
increase the size of the backpack by 1
repeat step 4 until you reach the desired size
Translated with www.DeepL.com