Skip to content

Instantly share code, notes, and snippets.

@thundergolfer
Last active September 29, 2017 07:36
Show Gist options
  • Select an option

  • Save thundergolfer/e5476b3c8a6253917f42ac822f44b5e7 to your computer and use it in GitHub Desktop.

Select an option

Save thundergolfer/e5476b3c8a6253917f42ac822f44b5e7 to your computer and use it in GitHub Desktop.
def unbounded_knapsack(items, C):
"""
items List[item], where 'item' is a named tuple -> (val=4, cost=10)
C int, where 'C' stands for capacity
Note: This implementation also stores the optimal group of items at each capacity value
"""
dp = [(0, [])] * (C + 1)
used = []
items.sort(key=lambda x: x.cost)
for c in range(1, C + 1):
best = 0
for item in items:
if item.cost <= c:
option = dp[c - item.cost][0] + item.val
if option > best:
best = option
used = dp[c - item.cost][1] + [item]
else:
break
dp[c] = (best, used)
return dp[C][0], dp[C][1]
@thundergolfer

Copy link
Copy Markdown
Author

Unbounded knapsack is where you can select an item from the candidate group more than once.

The code is actually almost more simple than 1/0 knapsack.

@thundergolfer

Copy link
Copy Markdown
Author

If you pre-sort the candidate items in ascending by cost, you can avoid looping pointlessly through the rest of the items if you find one is already too big for the current c.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment