Skip to content

Instantly share code, notes, and snippets.

@dongr0510
Created September 11, 2020 03:30
Show Gist options
  • Save dongr0510/04376e8c5fa9e72cda9e282402bd4149 to your computer and use it in GitHub Desktop.
Save dongr0510/04376e8c5fa9e72cda9e282402bd4149 to your computer and use it in GitHub Desktop.
def unbound_knapsack(profits, weights, capacity):
n = len(profits)
# base case
if capacity <= 0 or n == 0 or len(weights) != n:
return 0
dp = [[-1 for _ in range(capacity+1)] for _ in range(len(profits))]
# initiaite the capacity = 0 columns
for i in range(n):
dp[i][0] = 0
for i in range(n):
for c in range(1, capacity+1):
profit1, profit2 = 0, 0
if weights[i] <= c:
profit1 = profits[i] + dp[i][c - weights[i]]
if i > 0:
profif2 = dp[i-1][c]
dp[i][c] = max(profit1, profit2)
return dp[-1][-1]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment