Skip to content

Instantly share code, notes, and snippets.

@turtleizzy
Created December 1, 2020 13:12
Show Gist options
  • Select an option

  • Save turtleizzy/f49516df9551428fee7cca0a61cbcf61 to your computer and use it in GitHub Desktop.

Select an option

Save turtleizzy/f49516df9551428fee7cca0a61cbcf61 to your computer and use it in GitHub Desktop.
0-1 backpack dp in python
import numpy as np
numbers = np.array([67000, 48720, 222600, 27560, 2500000, 2120, 53446, 53000, 53000, 53000, 45077, 7977, 100000, 6382, 30605, 64782, 33485, 3697, 71056, 2515])
targetSum = 301925
arr = [np.zeros([targetSum+1], dtype=np.int), np.zeros([targetSum+1], dtype=np.int)]
curArr = 1
for i in range(len(numbers)):
curArr = 1 - curArr
if (i==0):
arr[curArr][numbers[i]] = 1
else:
arr[curArr] = arr[1-curArr]
t = np.concatenate([[numbers[i]], numbers[i] + np.where(arr[1-curArr]>0)[0]])
t = t[t<arr[curArr].shape[0]]
t = t[arr[curArr][t]==0]
arr[curArr][t] = i + 1
if arr[curArr][targetSum] > 0:
res = []
curSum = targetSum
curPick = arr[curArr][curSum] - 1
while curSum > 0:
res.append(curPick)
curSum -= numbers[curPick]
curPick = arr[curArr][curSum] - 1
print(numbers[res])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment