DSA
    advanced

    0/1 Knapsack Problem

    0/1 Knapsack Problem

    A combinatorial optimization problem: Given a set of items, each with a weight and a value, determine which items to include in a collection so that the total weight is less than or equal to a given limit and the total value is as large as possible.

    ⏱ O(nW)
    💾 O(nW)
    Playing
    01234567
    Base00000000
    I1(w:1,v:1)00
    1,1
    000000
    I2(w:3,v:4)00000000
    I3(w:4,v:5)00000000
    I4(w:5,v:7)00000000
    Capacity
    Item 1Wt: 1Val: 1
    Item 2Wt: 3Val: 4
    Item 3Wt: 4Val: 5
    Item 4Wt: 5Val: 7

    Checking Item 1 (Wt: 1, Val: 1) for Capacity 1

    500%

    Fill the knapsack table

    Sequence

    Order the steps of the 0/1 knapsack DP.

    Tap a piece, then tap where it goes — or drag it. Tap the tray to take one back.

    1. 1Drop a step here
    2. 2Drop a step here
    3. 3Drop a step here
    4. 4Drop a step here
    5. 5Drop a step here
    5 pieces left to place

    Test your knowledge

    20 questions
    Question 1 of 20
    Score: 0

    What does dp[i][w] represent?

    The short version

    Think of a thief robbing a store with a small backpack. He can't take everything. He must choose a combination of items that fits in the bag but has the highest total resale value.

    In more depth

    The Choice Diagram

    The Knapsack problem represents the classic Constraint Optimization pattern. For every item, you have a choice:

    1.Include it: Add its value, subtract its weight from capacity.
    2.Exclude it: Skip it, keep capacity same.

    We take the maximum of these two choices.

    0/1 vs Unbounded:

    0/1: Can use each item only once.
    Unbounded: Can use each item infinite times (like Coin Change).

    When to reach for this

    • Maximize value given a capacity constraint
    • Find if a subset sums to a Detailed Target
    • Min/Max number of ways to reach a target using elements

    Interview Questions

    Amazon
    Google
    Microsoft
    Facebook
    LinkedIn
    Facebook
    Amazon
    Uber
    Google
    Airbnb
    Palantir

    Love this visualization?

    Sign up to track your progress, earn achievements, use the AI assistant, and access your personal learning dashboard.

    100% free • No credit card required