Choosing the optimal combination of items under a strict capacity constraint.
The 0/1 Knapsack Problem gives you a bag with weight capacity W, and a list of items each with a weight and a value. You want to maximise the total value without busting the weight.
For every item, you have a choice: Skip it (carry over the max value for this capacity from previous items) or Take it (add its value to the max value of capacity - item.weight from previous items). The DP grid tracks dp[item][capacity].
def knapsack(W, weights, values):
n = len(weights)
dp = [[0] * (W + 1) for _ in range(n + 1)]
for i in range(1, n + 1):
for w in range(W + 1):
if weights[i-1] <= w:
# Take or Skip
dp[i][w] = max(
dp[i-1][w],
dp[i-1][w - weights[i-1]] + values[i-1]
)
else:
# Skip
dp[i][w] = dp[i-1][w]
return dp[n][W]