mediumDSA

How do you solve the 0/1 knapsack problem?

1.1k views
01

Understand the problem

Explain 0/1 knapsack DP.

dpknapsack
02

Attempt it yourself

Sketch your approach before reading the solution — that's what interviews test.

Stuck? AI Nudge Available

Get a conceptual hint to guide your logic without spoiling the final implementation.

03

Study the solution

The solution is waiting

Give it an honest attempt first — then compare your thinking with the full walkthrough.

04

Read the code

1-D DP, capacity swept downward
Run Playground
def knapsack(weights, values, capacity):
    dp = [0] * (capacity + 1)
    for i in range(len(weights)):
        for w in range(capacity, weights[i] - 1, -1):    # high -> low = 0/1
            dp[w] = max(dp[w], dp[w - weights[i]] + values[i])
    return dp[capacity]


# --- demo ---
weights = [1, 3, 4, 5]
values  = [1, 4, 5, 7]
print(knapsack(weights, values, 7))   # 9  (weights 3 + 4 -> values 4 + 5)
05

Join the discussion

Discussion (0)

Sign in to join the discussion.

No responses yet. Be the first to share what you think.