fork download
  1. $inventory = [
  2. {
  3. weight: 1,
  4. value: 1
  5. },
  6. {
  7. weight: 3,
  8. value: 4
  9. },
  10. {
  11. weight: 4,
  12. value: 5
  13. },
  14. {
  15. weight: 1,
  16. value: 7
  17. }
  18. ]
  19.  
  20. def max_loot(n)
  21. inventory = $inventory
  22. max_loot = [ [0] * (n+1) ] * (inventory.length)
  23.  
  24. solutions = []
  25.  
  26. (1...(n+1)).each do |weight|
  27. (0...inventory.length).each do |item|
  28. if weight >= inventory[item][:weight]
  29. item_value = inventory[item][:value] + max_loot[item - 1][weight - inventory[item][:weight]]
  30. max_loot[item][weight] = [
  31. item_value,
  32. max_loot[item - 1][weight]
  33. ].max
  34. else
  35. max_loot[item - 1][weight]
  36. end
  37. end
  38. end
  39.  
  40. return max_loot[-1][-1]
  41. end
  42.  
  43. puts max_loot(4)
Success #stdin #stdout 0.01s 6000KB
stdin
Standard input is empty
stdout
28