CodeBlanks Logo Icon CodeBlanks

Summary - Knapsack

Solve knapsack and print the best value in a mini task.

Summary - Knapsack

0/1 knapsack finds the max value with a 2D DP table and take/skip decisions. Used in resource allocation and investment decisions.

In this mini task you will solve knapsack and print the best value; combine all steps.

0/1 knapsack gives Θ(nW) time; if W is large it is called pseudo-polynomial.

Practice Print knapsack

Write knap_print(W, weights, values, n). Print the max value with DP and print(). Output of knap_print(50, [10, 20, 30], [60, 100, 120], 3): 220.

Starter code

solution.py
def knap_print(W, weights, values, n):
    # Print knapsack

Sample solution

solution.py
def knap_print(W, weights, values, n):
    # Print knapsack
    dp = [[0] * (W + 1) for _ in range(n + 1)]
    for i in range(1, n + 1):
        for w in range(1, W + 1):
            if weights[i - 1] <= w:
                dp[i][w] = max(dp[i - 1][w], values[i - 1] + dp[i - 1][w - weights[i - 1]])
            else:
                dp[i][w] = dp[i - 1][w]
    print(dp[n][W])
knap_print(50, [10, 20, 30], [60, 100, 120], 3)

Expected output

220

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Summary - Knapsack: match the terms

Term Meaning
knapsack Knapsack
DP Table
take Take
skip Skip

2 Weight check

Question
if weights[i - 1] <= ____:
Answer
if weights[i - 1] <= w:

Explanation: w is right.

3 Knapsack is an example of which area?

  • Backtracking
  • Greedy
  • Dynamic programming Correct answer
  • Divide and conquer

Explanation: Dynamic programming.

All lessons in Advanced