Complete the code to initialize the DP table with zeros.
dp = [[[1] for _ in range(capacity + 1)] for _ in range(n + 1)]
The DP table should be initialized with zeros because initially no items are taken, so the maximum value is zero.
Complete the code to check if the current item's weight fits in the current capacity.
if weights[i - 1] [1] w:
We check if the item's weight is less than or equal to the current capacity to decide if we can include it.
Fix the error in the code to correctly update the DP table when including the current item.
dp[i][w] = max(dp[i - 1][w], dp[i - 1][w - weights[i - 1]] [1] values[i - 1])
We add the current item's value to the best value without this item's weight to update the DP table.
Fill both blanks to complete the loop that builds the DP table.
for i in range(1, [1] + 1): for w in range(1, [2] + 1):
The outer loop runs over items (n), and the inner loop runs over capacities (capacity) to fill the DP table.
Fill all three blanks to complete the function that returns the maximum value for the knapsack.
def knapsack([1], [2], [3]): n = len(values) dp = [[0 for _ in range(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(dp[i - 1][w], dp[i - 1][w - weights[i - 1]] + values[i - 1]) else: dp[i][w] = dp[i - 1][w] return dp[n][capacity]
The function takes weights, values, and capacity as inputs to solve the knapsack problem.
