Files never leave your device

0/1 knapsack calculator

Choose items of maximum total value without reusing any item. Your inputs stay on your device.

Set up your task

Ready. Processing stays in this browser.

How to use 0/1 knapsack calculator

Choose items of maximum total value without reusing any item. The pre-filled problem gives you a worked starting point. Compare the response with your own working before trying the self-check below.

  1. Check the example inputs: Item weights, Item values, Maximum weight.
  2. Change the inputs for your problem. Results update as you type, so finish entering the values before copying an answer.
  3. Use the working to check an intermediate value or assumption. Then change the example as suggested in the self-check and compare the result.

Supported inputs and limits

Enter up to 30 matching weights and values. Weights are positive integers. Capacity is a whole number from 0 to 120.

How it works

The 0/1 knapsack problem assigns a weight and a value to each item. The goal is to maximise value while staying within capacity. The 0/1 restriction lets each particular item be included once or left out. Equal weights or values can still describe separate items.

For every row of the dynamic programme, compare leaving the current item out with adding it to the best earlier collection that fits the remaining space. Tracing the completed table backwards finds one optimal collection. The table grows with the numerical capacity, which explains the limit on that input.

Example

Run the pre-filled example. Its first result is “Maximum value: 11”.

Item weights
2 3 4 5
Item values
3 4 5 8
Maximum weight
7
Maximum value: 11
Chosen item positions: 1, 4
Weight used: 7 / 7
Each item is available once. On ties, the trace prefers leaving out the later item.

Questions about 0/1 knapsack calculator

Does each chosen position refer to the original list?

Yes. Positions start at 1 and match the order of the supplied weights and values.

Why does picking the highest value per unit weight sometimes fail?

Whole items may leave unused capacity. A cheaper item per unit can combine better with another one. The fractional variant, where splitting items is allowed, is a different optimisation problem.

Set the example capacity to 4.

Expect maximum value 5 from item position 3. Taking items of weights 2 and 3 together would exceed the capacity.

Related tools

Year 2: Algorithms and theory

Last updated