Skip to content
PixelCursor(opens in a new tab)
Computer Science

Knapsack Problem

Visualize and solve the knapsack optimization problem

Problem
  • Travel bag
  • Greedy trap
  • Day trip
  • Random items
Capacity
kg
Pack

Tap items on the shelf to pack them. Can you beat the computer?

Value00 / 7 kg0% full

    Empty. Tap an item below to pack it.

    Shelf (5)

    Big number: value. Below: weight and value per kg, one square per kg.

    Add your own item

    kg

    Weights are whole kilograms, so the table stays a table. Press Enter to add.

    The table behind the optimum

    Row by row, the table answers: what is the best value from the first items within w kg? Each cell either skips the item (the cell above) or takes it (value plus the best of what is left). The marked path, read from the bottom right, tells which items the optimum packs.

    Find the optimum to fill the table.

    About this tool

    • All or nothing

      In the 0/1 knapsack every item goes in whole or not at all. That one rule makes it hard: n items allow 2ⁿ different packings.

    • Small answers, big answer

      Dynamic programming solves every smaller bag once and reuses the answers. With whole weights that takes items × capacity steps instead of trying every packing.

    • Greedy is not enough

      Best value per kg first sounds clever and is often close. Load the greedy trap: one good item blocks two that are better together.

    Keyboard

    Space
    Find the optimum
    G
    Show the greedy packing
    M
    Show your packing
    N
    New random items
    U
    Unpack your bag