Knapsack 01 Dynamic Programming (Python)
Solve the 0-1 knapsack problem using dynamic programming with a one dimensional rolling array.
Code
def knapsack01(weights, values, capacity):
n = len(weights)
dp = [0] * (capacity + 1)
for i in range(n):
next_dp = [0] * (capacity + 1)
for w in range(capacity + 1):
next_dp[w] = dp[w]
if w >= weights[i] and dp[w - weights[i]] + values[i] > next_dp[w]:
next_dp[w] = dp[w - weights[i]] + values[i]
dp = next_dp
return dp[capacity]Report a problem with this exampleOpens a pre-filled issue on GitHub.