ALGORITHMS
🇬🇧UK Edition🇨🇦Canada Edition🌐Global Tech
0/1 Knapsack Problem: Bottom-Up Dynamic Programming Solution
Elena Rostova
Staff Engineer & Algorithmic Specialist
Updated 03/09/20267 min read0 views
Problem Statement
Given weights and values of N items, put these items in a knapsack of capacity W to get the maximum total value.
python
def knapsack(weights, values, capacity):
n = len(weights)
dp = [[0] * (capacity + 1) for _ in range(n + 1)]
for i in range(1, n + 1):
for w in range(1, capacity + 1):
if weights[i-1] <= w:
dp[i][w] = max(values[i-1] + dp[i-1][w - weights[i-1]], dp[i-1][w])
else:
dp[i][w] = dp[i-1][w]
return dp[n][capacity]
weights = [1, 2, 3]
values = [60, 100, 120]
print("Max Value:", knapsack(weights, values, 5))Frequently Asked Questions (FAQ)
Q: Can space complexity be optimized to O(W)?
Yes, by maintaining only a 1D DP array for the previous row.
Written by Elena RostovaAdSense EEAT Verified
Staff Engineer & Algorithmic Specialist. Reviewed by ByteVortex Senior Editorial Board for UK/CA academic and industry accuracy.