AdvancedAbout 25 min

    0/1 Knapsack Problem

    Read the full article on Substack

    8 min read.

    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.

    Think of it this way: 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.

    01234567—1: 1/12: 3/43: 4/54: 5/700000000

    Row 0: with no items, every capacity is worth 0.

    1/38

    Check your understanding

    Answer from memory before you scroll back up. Pulling an idea out of your head is what makes it stay there.

    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

    Quiz

    20 questions
    Question 1 of 20
    Score: 0

    What does dp[i][w] represent?

    Done with this lesson?

    Sign in free to keep your progress, streak and quiz scores.

    Keep going