$inventory = [
{
weight: 1,
value: 1
},
{
weight: 3,
value: 4
},
{
weight: 4,
value: 5
},
{
weight: 1,
value: 7
}
]
def max_loot(n)
inventory = $inventory
max_loot = [ [0] * (n+1) ] * (inventory.length)
solutions = []
(1...(n+1)).each do |weight|
(0...inventory.length).each do |item|
if weight >= inventory[item][:weight]
item_value = inventory[item][:value] + max_loot[item - 1][weight - inventory[item][:weight]]
max_loot[item][weight] = [
item_value,
max_loot[item - 1][weight]
].max
else
max_loot[item - 1][weight]
end
end
end
return max_loot[-1][-1]
end
puts max_loot(4)
JGludmVudG9yeSA9IFsKICAgIHsKICAgICAgICB3ZWlnaHQ6IDEsCiAgICAgICAgdmFsdWU6IDEKICAgIH0sCiAgICB7CiAgICAgICAgd2VpZ2h0OiAzLAogICAgICAgIHZhbHVlOiA0CiAgICB9LAogICAgewogICAgICAgIHdlaWdodDogNCwKICAgICAgICB2YWx1ZTogNQogICAgfSwKICAgIHsKICAgICAgICB3ZWlnaHQ6IDEsCiAgICAgICAgdmFsdWU6IDcKICAgIH0KXQoKZGVmIG1heF9sb290KG4pCiAgICBpbnZlbnRvcnkgPSAkaW52ZW50b3J5CiAgICBtYXhfbG9vdCA9IFsgWzBdICogKG4rMSkgXSAqIChpbnZlbnRvcnkubGVuZ3RoKQogICAgCiAgICBzb2x1dGlvbnMgPSBbXQoKICAgICgxLi4uKG4rMSkpLmVhY2ggZG8gfHdlaWdodHwKICAgICAgICAoMC4uLmludmVudG9yeS5sZW5ndGgpLmVhY2ggZG8gfGl0ZW18CiAgICAgICAgICAgIGlmIHdlaWdodCA+PSBpbnZlbnRvcnlbaXRlbV1bOndlaWdodF0KICAgICAgICAgICAgICAgIGl0ZW1fdmFsdWUgPSBpbnZlbnRvcnlbaXRlbV1bOnZhbHVlXSArIG1heF9sb290W2l0ZW0gLSAxXVt3ZWlnaHQgLSBpbnZlbnRvcnlbaXRlbV1bOndlaWdodF1dCiAgICAgICAgICAgICAgICBtYXhfbG9vdFtpdGVtXVt3ZWlnaHRdID0gWwogICAgICAgICAgICAgICAgICAgIGl0ZW1fdmFsdWUsCiAgICAgICAgICAgICAgICAgICAgbWF4X2xvb3RbaXRlbSAtIDFdW3dlaWdodF0KICAgICAgICAgICAgICAgIF0ubWF4CiAgICAgICAgICAgIGVsc2UKICAgICAgICAgICAgICAgIG1heF9sb290W2l0ZW0gLSAxXVt3ZWlnaHRdCiAgICAgICAgICAgIGVuZCAgICAgICAKICAgICAgICBlbmQKICAgIGVuZAoKICAgIHJldHVybiBtYXhfbG9vdFstMV1bLTFdCmVuZAoKcHV0cyBtYXhfbG9vdCg0KQ==