Explain Knapsack Problem with Example: Simple Guide

Logan Jul 13, 2026

The knapsack problem is a classic optimization problem that has captivated computer scientists and mathematicians alike for its simplicity and challenge. It's all about maximizing a certain value while adhering to a capacity constraint, a scenario that naturally arises in various real-world applications, from resource allocation to shopping bag selection.

0-1 Knapsack Problem
0-1 Knapsack Problem

At its core, the knapsack problem poses a fundamental question: given a set of items, each with a unique value and weight, and a knapsack with a limited capacity, how do you maximize the total value of the items you can carry in the knapsack? It's not just about greedily selecting the most valuable items; you must also consider the weight they add to the knapsack. Let's delve into this problem further with practical examples.

a drawing of a man with a backpack and crutches standing next to an instrument
a drawing of a man with a backpack and crutches standing next to an instrument

Understanding the Knapsack Problem

To get a handle on the knapsack problem, let's first understand its formal definition. Let's have 'n' items, where each item 'i' has a value 'Vi' and a weight 'Wi'. We're given a knapsack with a maximum capacity of 'C'. The objective is to find a subset of items to include in the knapsack that maximizes the total value, subject to the constraint that the total weight of the items doesn't exceed the knapsack's capacity:

What Is the Best Way to Pack a Backpack
What Is the Best Way to Pack a Backpack

Maximize ∑(Vi * Xi)

Subject to ∑(Wi * Xi) ≤ C

Math Problem Solving Strategies Classroom Math Poster, Classroom Math Teaching Ideas, Elementary Math Strategies, How To Teach Math Problem-solving, Math Problem Solving Strategies Poster, First Grade Math Projects, Word Problem Strategies Anchor Chart, Problem Solving Strategies Anchor Chart, Math Problem Solving Chart
Math Problem Solving Strategies Classroom Math Poster, Classroom Math Teaching Ideas, Elementary Math Strategies, How To Teach Math Problem-solving, Math Problem Solving Strategies Poster, First Grade Math Projects, Word Problem Strategies Anchor Chart, Problem Solving Strategies Anchor Chart, Math Problem Solving Chart

And Xi {0, 1} for all i, meaning each item can either be included (Xi = 1) or excluded (Xi = 0) from the knapsack.

Zero-One Knapsack Problem

The most well-known version of the knapsack problem is the zero-one knapsack problem, where each item can be taken either in its entirety or not at all. This can be modeled using binary variables Xi, as shown in the objective function above. A classic example involves a treasure hunter selecting the most valuable treasures to take from a cave, given the weight limit of his bag. Let's say our hunter, A Gertrude, has the following treasures to choose from:

a flow diagram with different types of items in the process and instructions on how to use them
a flow diagram with different types of items in the process and instructions on how to use them
  • Gold Bar (V1=4, W1=1) - 4 units of value, 1 unit of weight
  • Gemstone (V2=7, W2=3) - 7 units of value, 3 units of weight
  • Silver Coin (V3=3, W3=1) - 3 units of value, 1 unit of weight
  • Emerald Ring (V4=6, W4=2) - 6 units of value, 2 units of weight
  • Crown Jewel (V5=10, W5=5) - 10 units of value, 5 units of weight

Gertrude's bag has a weight limit of 6 units. If Gertrude were to include all the treasures with values exceeding 2 (Gold Bar, Gemstone, Emerald Ring, and Crown Jewel), she would end up with a total value of 27 but a weight of 11, exceeding her bag's limit. She must therefore strategically choose her treasures to maximize her total value without exceeding 6 units of weight. We'll return to Gertrude's dilemma later when we discuss solution approaches.

Bounded Knapsack Problem

How to Solve Any Problem in 5 Simple Steps
How to Solve Any Problem in 5 Simple Steps

A variant of the knapsack problem is the bounded knapsack problem, where each item has a specific number of units, denoted as Ni, that Gertrude can take. This version of the problem introduces an additional constraint to the optimization problem: ∑(Xi * Ni) ≤ NiMax for all i, where NiMax is the maximum number of units of item i Gertrude can take. For instance, Gertrude might have a maximum of 2 gold bars she can reasonably carry. In such cases, we revisit our treasure-hunting scenario, with Gertrude still constrained by her bag's 6-unit weight limit:

Item (i)Value (Vi)Weight (Wi)Maximum Units (NiMax)
Gold Bar412
Gemstone731
Silver Coin313
Emerald Ring621
Crown Jewel1051
PROCESS: LOST COAST | Boreas Gear
PROCESS: LOST COAST | Boreas Gear
What Heavy Backpacks Are Doing To Kids' Bodies
What Heavy Backpacks Are Doing To Kids' Bodies
Problem-Solving Strategies: Definition and 5 Techniques to Try
Problem-Solving Strategies: Definition and 5 Techniques to Try
Tokyo Bosai - A Manual for Disaster Preparedness
Tokyo Bosai - A Manual for Disaster Preparedness
Sack It!
Sack It!
the instructions to make a drawsack bag for someone who is holding something in their hand
the instructions to make a drawsack bag for someone who is holding something in their hand
Problem-solving Steps Guide, How To Improve Problem Solving Skills, Problem-solving Tips, How To Improve Math Problem-solving Skills, How To Solve Problems, Daily Problem-solving Tips, How To Solve Daily Problems, How To Solve Common Problems, Motivational Problem-solving Tips
Problem-solving Steps Guide, How To Improve Problem Solving Skills, Problem-solving Tips, How To Improve Math Problem-solving Skills, How To Solve Problems, Daily Problem-solving Tips, How To Solve Daily Problems, How To Solve Common Problems, Motivational Problem-solving Tips
Problem Size vs Reaction Size and How to Teach It - A Fresh Breath on Teaching
Problem Size vs Reaction Size and How to Teach It - A Fresh Breath on Teaching
Projects. Simple Hike Kit Or Pouch Bag
Projects. Simple Hike Kit Or Pouch Bag
the four basic rules for using addition and subtractions to solve an important problem
the four basic rules for using addition and subtractions to solve an important problem
Big Problems vs Small Problems, Problem Solving Tools, Big & Small Problems
Big Problems vs Small Problems, Problem Solving Tools, Big & Small Problems
How Big is My Problem (SEL Worksheets): Help Kids Learn to Assess the Size of a Problem
How Big is My Problem (SEL Worksheets): Help Kids Learn to Assess the Size of a Problem
Troop 60 - First Aid Activities
Troop 60 - First Aid Activities
Girl problems
Girl problems
real
real
How to solve difficult (complex) problems
How to solve difficult (complex) problems
PRINTABLE Problem Scales
PRINTABLE Problem Scales
Snapsack ľahko, rýchlo a hlavne lacno
Snapsack ľahko, rýchlo a hlavne lacno
a printable book about cookies with the words think about it in black and white
a printable book about cookies with the words think about it in black and white
a man in a tie is talking to two other men at a desk with a chalkboard behind him
a man in a tie is talking to two other men at a desk with a chalkboard behind him

Now, Gertrude must not only consider the value-to-weight ratio of each treasure but also the number of units she can effectively carry while optimizing her haul's total value.

Solving the Knapsack Problem

The knapsack problem is a classic combinatorial optimization problem, best solved via methods known for their ability to handle such problems: dynamic programming, branch and bound, and greedy algorithms. Each approach offers a unique perspective on tackling the problem, with trade-offs between accuracy, efficiency, and implementational complexity.

Dynamic Programming Solution

Dynamic programming is an elegant and efficient way to solve the knapsack problem, reducing the number of computations necessary by storing the results of subproblems. The dynamic programming solution involves creating a table K[i][w], where K[i][w] represents the maximum value Gertrude can get by including the first 'i' items in the knapsack of capacity 'w'. The table can be computed recursively, taking O(nC) time:

K[i][w] = max {K[i-1][w], V[i] + K[i-1][w - W[i]]} if W[i] ≤ w

K[i][w] = K[i-1][w] otherwise

We initialize the table with K[0][w] = 0 for all 'w', and the solution is found at K[n][C]. Using this method, Gertrude could easily work out the maximum value she can achieve while respecting her bag's weight constraint. Dinhttps://www.math.harvard.edu/rifi erwing she to our earlier example, the dynamic programming table would look like this:

Weight Limit
Treasures123456
None000000
Gold Bar444444
Gemstone007777
Silver Coin366666
Emerald Ring036101010
Crown Jewel000101420

Thus, Gertrude's optimal solution involves taking the Crown Jewel and the Emerald Ring, giving her a total value of 20 while not exceeding the bag's weight limit of 6 units.

Greedy Algorithm Approach

A simple, intuitive solution to the knapsack problem is a greedy algorithm. In this case, Gertrude would continually select the item with the highest value-to-weight ratio until her bag's capacity is reached. The algorithm is straightforward to implement and runs in O(n log n) time, but its efficacy depends on the specific problem instance:

  1. Sort the items in decreasing order by their value-to-weight ratio, Vi/Wi.
  2. Initialize Wît = 0, total value = 0, and a list called items = {}.
  3. While Wît < C (bag's weight limit) and items isn't empty:
    • Select the treasure 'i' with the highest value-to-weight ratio from items.
    • If Wít + Wi ≤ C, add Vi to total value, decrease C by Wi, and set Wít = Wít + Wi. Remove 'i' from items.
    • Otherwise, add (C - Wít) * Vi/Wi to total value, break the loop, and go to step 4.

  • Return total value as the optimal value.
  • Using this greedy approach for Gertrude's treasure hunt, she initially takes the Crown Jewel (V5 = 10, W5 = 5, ratio = 2), followed by the Emerald Ring (V4 = 6, W4 = 2, ratio = 3), giving her a total value of 16. However, this falls short of the optimal solution obtained with dynamic programming. Greedy algorithms make no guarantees about the global optimum; they merely provide a quick, locally optimal solution.

    Exploring these solution methods reveals the knapsack problem's rich computational landscape, showcasing efficient algorithms for making optimal decisions under constraints. From shopping bag dilemmas to scheduling problems, the knapsack problem offers a gold mine of insights and practical applications.

    To further explore the knapsack problem, consider examining the effect of item heaviness on the optimal solution. Would Gertrude's strategy change if the Crown Jewel suddenly weighed twice as much? Engaging with such 'what-if' scenarios not only hones your problem-solving prowess but also deepens your understanding of the knapsack problem's subtleties. Happy treasure hunting!