Understanding and Implementing the Knapsack Problem (0/1)
By Mukesh Kumar
Updated on Mar 26, 2025 | 24 min read | 1.3k views
Share:
For working professionals
For fresh graduates
More
By Mukesh Kumar
Updated on Mar 26, 2025 | 24 min read | 1.3k views
Share:
Table of Contents
The Knapsack Problem is a powerful optimization tool used to make the most of limited resources. For instance, in logistics and resource allocation, it helps businesses determine which items to prioritize. This could be packing a truck, budgeting for a project, or selecting investments—it ensures maximum value under strict constraints.
In this blog, you’ll explore the core concepts of the Knapsack Problem, including its different variations and approaches to solving it.
The 0/1 Knapsack Problem is a classic optimization challenge in computer science and operations research. Imagine you have a knapsack with a limited weight capacity, and you're presented with a set of items, each having a specific weight and associated profit.
Here are its key features:
However, for moderate input sizes, efficient algorithms like dynamic programming can provide optimal solutions within reasonable time frames, making it a practical approach for many real-world applications.
The goal of the 0/1 Knapsack Problem is to determine the most profitable combination of items to include in the knapsack. This is while staying within constraints such as weight, cost, or space—depending on the specific application.
These constraints help ensure that the selection optimizes the use of limited resources, whether it's for cargo loading, project budgeting, or investment allocation.
Problem Breakdown:
Given: A knapsack with a maximum weight capacity, denoted as W. It consists of a list of items, each characterized by:
Objective: Select a subset of items such that the combined weight of the selected items does not exceed the knapsack's capacity W. Ensure the total profit of the selected items is maximized.
Example Scenario: Consider a knapsack with a capacity of W = 4 units. You're provided with three items:
Analysis:
Therefore, the optimal solution is to select Item 3, resulting in a maximum profit of 3.
Key Considerations:
This problem exemplifies decision-making under constraints and has widespread applications in resource allocation, budgeting, and cargo loading, where optimal selection is crucial for efficiency and profitability.
Now that you have a solid understanding of the Knapsack Problem, let's dive into how to implement it step-by-step.
Implementing the Knapsack Problem involves building an optimal solution by evaluating each item's contribution, understanding state transitions, and optimizing calculations.
This approach is key in real-world applications like budget allocation, inventory management, and project scheduling. Here, managing resource constraints is critical to maximizing value.
Let's break down how you can solve a simple Knapsack Problem using a real example. This example will help us understand the steps clearly as you go through them.
Example: You have a knapsack that can carry up to 5 units of weight, and you have three items to choose from. Each item has a weight and a value, and you need to figure out which items to select in order to maximize the total value of the knapsack, without exceeding its weight capacity.
Here are the details:
The capacity of the knapsack is 5 units.
You need to choose a combination of these items to maximize the value of the knapsack without exceeding the weight limit.
You will use a 2D Dynamic Programming (DP) table. Here, dp[i][j] will represent the maximum value achievable with the first i items and a knapsack capacity of j.
The table will have (n+1) rows, where n is the number of items, and (W+1) columns, where W is the weight capacity. The extra row and column account for the base case where no items are selected, or the weight capacity is zero.
For example, with 3 items and a knapsack capacity of 5, the table will be a 4x6 grid (4 rows and 6 columns). The first row and column are initialized to 0, as the maximum value with 0 items or a 0 weight capacity is always 0.
Initial DP table:
0 1 2 3 4 5
0 0 0 0 0 0 0
1 0 0 0 0 0 0
2 0 0 0 0 0 0
3 0 0 0 0 0 0
Also Read: What are Data Structures & Algorithm
Now, let's go through each item and each possible capacity to fill up the table.
For Item 1 (Weight = 2, Value = 3):
After considering Item 1:
0 1 2 3 4 5
0 0 0 0 0 0 0
1 0 0 3 3 3 3
2 0 0 0 0 0 0
3 0 0 0 0 0 0
For Item 2 (Weight = 3, Value = 4):
After considering Item 2:
0 1 2 3 4 5
0 0 0 0 0 0 0
1 0 0 3 3 3 3
2 0 0 3 4 4 7
3 0 0 0 0 0 0
For Item 3 (Weight = 4, Value = 5):
After considering Item 3:
0 1 2 3 4 5
0 0 0 0 0 0 0
1 0 0 3 3 3 3
2 0 0 3 4 4 7
3 0 0 3 4 5 7
After populating the table, the maximum value we can achieve with a knapsack capacity of 5 is located in dp[3][5], which is 7. This value represents the highest profit achievable by considering all three items while staying within the weight limit of 5.
In other words, dp[3][5] reflects the optimal combination of items, balancing both their weight and profit, to maximize the value without exceeding the knapsack's capacity.
To find which items were selected, you can trace back from dp[3][5]. The value at dp[3][5] (which is 7) is the same as dp[2][5]. This means Item 3 was not included.
Thus, the selected items are:
The maximum value you can carry in the knapsack is 7, and we achieve this by selecting Item 1 and Item 2. This process uses dynamic programming to efficiently solve the problem by breaking it down into smaller subproblems and building the solution incrementally.
Also Read: Data Structures in Javascript Explained: Importance, Types & Advantages
With a clear understanding of implementing the Knapsack Problem, let’s dive deeper into the different variants and optimizations available.
The Knapsack Problem comes in different forms and optimizations, each solving a variation of the basic problem where you need to maximize profit while respecting a weight limit.
Below are the key variants and optimization techniques for solving the knapsack problem:
In the 0-1 Knapsack Problem, each item can either be included or excluded from the knapsack. The challenge is to maximize the total value without exceeding the knapsack's capacity.
Dynamic Programming Transition:
For each item i, you have two options:
Transition Equation:
f[j] = max(f[j], f[j - w[i]] + v[i])
Implementation:
In the Complete Knapsack Problem, an item can be included an unlimited number of times, unlike the 0-1 knapsack where each item is considered once. The goal remains to maximize the total value.
Transition Equation:
f[j] = max(f[j], f[j - w[i]] + v[i])
This allows the selection of an item multiple times, making it possible to fill the knapsack more flexibly.
Implementation:
In the Multiple Knapsack Problem, each item has a limited quantity available for selection. Instead of only considering whether an item is taken or not, you can take it up to a certain number of times.
Transition Equation:
f[j] = max(f[j], f[j - k * w[i]] + k * v[i])
Where k represents the number of times an item is taken.
Time Complexity:
To optimize the time complexity of the multiple knapsack problem, we can use Binary Grouping. This splits each item into powers of 2, reducing repetitive calculations.
Splitting Approach: If an item i can be taken k_i times, split it into smaller groups using binary powers: 2^0, 2^1, ..., 2^j and then solve with 0-1 knapsack.
Time Complexity:
For the Multiple Knapsack problem, Monotone Queue Optimization can further speed up the solution by maintaining a queue that stores the optimal solution for each possible weight.
Optimized Transition:
g[x, y] = max(g[x - k, y] + v_i * k)
This reduces the complexity to O(n * W).
The Mixed Knapsack Problem is a combination of the above types where some items can be taken only once, some infinitely, and others at most k times.
This problem can be solved by combining the techniques from 0-1 knapsack, complete knapsack, and multiple knapsack.
Here's a table differentiating each of the 6 types of knapsack problems:
Knapsack Type |
Item Selection |
Item Repetition |
Typical Use Case |
0-1 Knapsack | Each item is either included or excluded | No repetition (0 or 1) | Standard optimization problems (e.g., packing) |
Complete Knapsack | Items can be selected multiple times | Yes (unlimited) | Resource allocation where items can be reused (e.g., manufacturing) |
Multiple Knapsack | Each item has a limited quantity available | Yes (up to k times) | Inventory management with limited stock of each item |
Binary Grouping Optimization | Same as multiple knapsack, but with optimizations | Yes (via binary splitting) | Large-scale optimization problems with high item repetition |
Monotone Queue Optimization | Same as multiple knapsack but optimized using a queue | Yes (up to k times) | Complex knapsack with improved efficiency using queue management |
Mixed Knapsack | Items can be selected once, infinitely, or up to a certain number | Yes (mixed types) | Problems combining different types of item selection (e.g., mixed stock management) |
These techniques allow us to solve different knapsack variations efficiently, depending on the problem's requirements. Understanding each approach and applying the right optimization strategy can greatly improve performance in real-world applications.
Also Read: Data Structures & Algorithm in Python: Everything You Need to Know
After understanding the various Knapsack Problem variants, you can now dive into the different approaches for solving the 0/1 Knapsack.
The 0/1 Knapsack Problem can be solved using different approaches, each suited to specific problem sizes and resource constraints. The naive recursive approach is simple but inefficient for large datasets due to its exponential time complexity.
Dynamic Programming (DP) methods, such as top-down (memoization) and bottom-up (tabulation), improve efficiency with a time complexity of O(n × W).
For memory-constrained environments, the space-optimized DP approach further reduces space complexity. The choice of method depends on problem size, memory availability, and performance needs.
Let’s go through each of them in detail:
A straightforward method involves recursively exploring all possible subsets of items to find the one with the maximum profit without exceeding the capacity. This approach has an exponential time complexity of O(2^n) due to the evaluation of all subsets, making it inefficient for larger datasets.
Code:
#include <bits/stdc++.h>
using namespace std;
// Function to calculate maximum profit using recursion
int knapsackRec(int W, vector<int>& val, vector<int>& wt, int n) {
// Base case: no items left or capacity is zero
if (n == 0 || W == 0)
return 0;
// If weight of the nth item is more than capacity, it cannot be included
if (wt[n - 1] > W)
return knapsackRec(W, val, wt, n - 1);
// Calculate profit if nth item is included
int include = val[n - 1] + knapsackRec(W - wt[n - 1], val, wt, n - 1);
// Calculate profit if nth item is not included
int exclude = knapsackRec(W, val, wt, n - 1);
// Return the maximum of both choices
return max(include, exclude);
}
int main() {
vector<int> val = {1, 2, 3}; // Profits
vector<int> wt = {4, 5, 1}; // Weights
int W = 4; // Knapsack capacity
cout << "Maximum Profit: " << knapsackRec(W, val, wt, val.size()) << endl;
return 0;
}
Explanation:
Output:
Maximum Profit: 3
Also Read: Learn Naive Bayes Algorithm For Machine Learning [With Examples]
To optimize the recursive approach, we can use memoization to store the results of subproblems and avoid redundant calculations. This technique improves the time complexity to O(n × W), where 'n' is the number of items and 'W' is the knapsack's capacity.
Code:
#include <bits/stdc++.h>
using namespace std;
// Function to calculate maximum profit using memoization
int knapsackRec(int W, vector<int>& val, vector<int>& wt, int n, vector<vector<int>>& memo) {
// Base case: no items left or capacity is zero
if (n == 0 || W == 0)
return 0;
// If this subproblem has already been solved, return the stored result
if (memo[n][W] != -1)
return memo[n][W];
// If weight of the nth item is more than capacity, it cannot be included
if (wt[n - 1] > W)
return memo[n][W] = knapsackRec(W, val, wt, n - 1, memo);
// Calculate profit if nth item is included
int include = val[n - 1] + knapsackRec(W - wt[n - 1], val, wt, n - 1, memo);
// Calculate profit if nth item is not included
int exclude = knapsackRec(W, val, wt, n - 1, memo);
// Return the maximum of both choices and store the result
return memo[n][W] = max(include, exclude);
}
int main() {
vector<int> val = {1, 2, 3}; // Profits
vector<int> wt = {4, 5, 1}; // Weights
int W = 4; // Knapsack capacity
int n = val.size();
// Initialize memoization table with -1
vector<vector<int>> memo(n + 1, vector<int>(W + 1, -1));
cout << "Maximum Profit: " << knapsackRec(W, val, wt, n, memo) << endl;
return 0;
}
Explanation:
Output:
Maximum Profit: 3
In this approach, we build a table in a bottom-up manner, where each entry of the table represents the solution to a subproblem. The idea is to break down the problem into smaller subproblems, solve each of them, and then use those solutions to build up to the final solution.
The solution is computed iteratively by filling each entry in the table based on previously computed solutions to smaller subproblems. This ensures that each combination of items and weights is considered.
Code:
#include <bits/stdc++.h>
using namespace std;
// Function to calculate the maximum profit using bottom-up dynamic programming
int knapsack(int W, vector<int>& val, vector<int>& wt) {
int n = val.size(); // Number of items
vector<vector<int>> dp(n + 1, vector<int>(W + 1, 0)); // DP table initialization
// Building the DP table
for (int i = 1; i <= n; ++i) {
for (int w = 1; w <= W; ++w) {
if (wt[i - 1] <= w) { // If the current item can fit into the knapsack
dp[i][w] = max(dp[i - 1][w], val[i - 1] + dp[i - 1][w - wt[i - 1]]);
} else {
dp[i][w] = dp[i - 1][w]; // If the current item can't fit, don't pick it
}
}
}
// The value in dp[n][W] contains the maximum profit
return dp[n][W];
}
int main() {
vector<int> val = {1, 2, 3}; // Profits of the items
vector<int> wt = {4, 5, 1}; // Weights of the items
int W = 4; // Capacity of the knapsack
// Call the knapsack function and output the result
cout << "Maximum Profit: " << knapsack(W, val, wt) << endl;
return 0;
}
Explanation:
Output:
Maximum Profit: 3
Further optimization can be achieved by observing that, at any point, we only need information from the current and previous rows of the table. By storing only these rows, we can reduce the space complexity from O(n × W) to O(W), maintaining the same time complexity.
Code:
#include <bits/stdc++.h>
using namespace std;
// Function to calculate the maximum profit using space-optimized dynamic programming
int knapsack(int W, vector<int>& val, vector<int>& wt) {
int n = val.size(); // Number of items
vector<int> dp(W + 1, 0); // DP array initialization (for the current row)
// Iterate through each item
for (int i = 0; i < n; ++i) {
// Traverse the DP array backwards (from right to left)
for (int w = W; w >= wt[i]; --w) {
// Update the current dp[w] based on whether we include the current item or not
dp[w] = max(dp[w], dp[w - wt[i]] + val[i]);
}
}
// The value in dp[W] contains the maximum profit
return dp[W];
}
int main() {
vector<int> val = {1, 2, 3}; // Profits of the items
vector<int> wt = {4, 5, 1}; // Weights of the items
int W = 4; // Capacity of the knapsack
// Call the knapsack function and output the result
cout << "Maximum Profit: " << knapsack(W, val, wt) << endl;
return 0;
}
Explanation:
Output:
Maximum Profit: 3
This approach significantly reduces space complexity while maintaining the same time efficiency as the traditional bottom-up dynamic programming approach.
Also Read: What Is Coding? A 2025 Guide for Software Engineers
The Fractional Knapsack Problem allows for breaking items into fractions to maximize the total profit in a knapsack with a given weight capacity. Unlike the 0/1 knapsack problem, where items must be included or excluded entirely, this problem lets you take fractions of items to maximize value.
To solve the fractional knapsack problem efficiently, we use a greedy approach. The core idea is to select items based on their profit-to-weight ratio, and then take them fully or fractionally until the knapsack is full.
Steps:
Code Implementation:
#include <bits/stdc++.h>
using namespace std;
// Structure to store the profit and weight of each item
struct Item {
int profit, weight;
// Constructor
Item(int profit, int weight) {
this->profit = profit;
this->weight = weight;
}
};
// Comparison function to sort items based on profit/weight ratio
static bool cmp(Item a, Item b) {
double r1 = (double)a.profit / (double)a.weight;
double r2 = (double)b.profit / (double)b.weight;
return r1 > r2;
}
// Function to solve the fractional knapsack problem
double fractionalKnapsack(int W, Item arr[], int N) {
// Sort items by profit/weight ratio in decreasing order
sort(arr, arr + N, cmp);
double finalValue = 0.0;
// Traverse through all items
for (int i = 0; i < N; i++) {
// If item can fit in the knapsack, add it fully
if (arr[i].weight <= W) {
W -= arr[i].weight;
finalValue += arr[i].profit;
}
// Otherwise, add the fraction of the item that fits
else {
finalValue += arr[i].profit * ((double)W / (double)arr[i].weight);
break; // Knapsack is full, exit
}
}
return finalValue;
}
int main() {
int W = 50; // Knapsack capacity
Item arr[] = {{60, 10}, {100, 20}, {120, 30}}; // Items: {profit, weight}
int N = sizeof(arr) / sizeof(arr[0]);
// Call the fractional knapsack function and print the result
cout << "Maximum Profit: " << fractionalKnapsack(W, arr, N) << endl;
return 0;
}
Explanation:
Example 1
1. Input:
2. Calculate Profit/Weight Ratios:
3. Sort Items by Ratio:
4. Knapsack Filling:
Output:
Maximum Profit: 240
Example 2:
1. Input:
2. Calculate Profit/Weight Ratio:
3. Sort Items by Ratio:
4. Knapsack Filling:
Output:
Maximum Profit: 166.667
This greedy approach provides an efficient solution to the fractional knapsack problem and works best when fractional selection of items is allowed.
Also Read: Mastering the Fractional Knapsack Problem: A Guide to Optimizing Resource Allocation
With a clear understanding of the different problem-solving approaches, it’s time to dive into the real-world applications of the Knapsack Problem.
The Knapsack Problem is not just an academic exercise; it has numerous real-world applications across various industries. The essence of the knapsack problem is finding an optimal solution under a set of constraints, making it highly applicable to problems in resource allocation, logistics, finance, and more.
Here are some key real-world applications of knapsack problem:
1. Resource Allocation in Manufacturing
In manufacturing, the knapsack problem helps in deciding the optimal distribution of resources (materials, machines, time) across various production tasks. For instance, the problem can be modeled using the 0-1 knapsack, where each production task (item) has a certain material requirement (weight) and profit (value).
The algorithm helps select the best combination of tasks that maximize profit while staying within the available resource capacity.
2. Budget Allocation in Project Management
Budget allocation in project management is modeled as a knapsack problem where the goal is to allocate a fixed budget across several projects, each with a cost and expected return.
By using dynamic programming, companies can determine the optimal set of projects that maximize the total return. They can adhere to the budget constraint, ensuring resource optimization.
3. Cargo Loading in Logistics and Transportation
Logistics companies use the knapsack problem to determine which goods to load into a truck or shipping container, based on their weight and value. You can sort the goods according to their value-to-weight ratio.
The greedy or dynamic programming approaches can be used. You can maximize profit by optimizing the selection of items that fit within the available space or weight limits of the vehicle.
4. Portfolio Optimization in Finance
In finance, the knapsack problem is used for portfolio optimization, where each asset (stock, bond, etc.) has a cost (weight) and an expected return (value). The knapsack model helps investors select the optimal set of assets to maximize returns while adhering to constraints like risk or budget.
The dynamic programming approach ensures that the best combination of assets is chosen to fit within the risk tolerance and budget constraints.
5. Cargo and Passenger Scheduling in Airlines
Airlines use knapsack algorithms to optimize the loading of cargo and scheduling of passengers. By treating each passenger or cargo item as an "item" in the knapsack, airlines can maximize their revenue by efficiently utilizing available space and weight capacity.
The problem can be solved using dynamic programming to ensure the best combination of passengers and cargo is selected.
6. Data Compression and File Storage
In data compression, the knapsack problem is used to select a subset of files that maximize the value (usefulness) while minimizing the total size.
For example, a storage system might use dynamic programming to determine the best combination of files to store in a limited amount of space. This ensures maximum storage efficiency without exceeding capacity.
7. Knapsack Problem in Cryptography
Cryptography uses variations of the knapsack problem in encryption algorithms. It selects items (numbers) based on a knapsack-type problem.
Cryptosystems can securely hide information in a way that is computationally difficult to break, thus enhancing data security.
8. Cutting Stock Problem in Manufacturing
The cutting stock problem in manufacturing uses knapsack algorithms to determine the optimal way to cut large sheets of material (e.g., paper, metal) into smaller pieces while minimizing waste.
By using dynamic programming, manufacturers can efficiently allocate material to meet customer orders and minimize scrap.
9. Job Scheduling in Computing
In computing, job scheduling problems are often modeled as knapsack problems. Here, jobs are items, and the time taken to execute each job is the weight. The goal is to maximize the number of completed jobs within the available processor time.
Dynamic programming can be applied to optimize the order and selection of jobs that fit within the available computational resources.
The ability to model real-life scenarios using knapsack algorithms makes it a critical component of decision-making in various sectors.
Also Read: 20 Most Popular Programming Languages in 2025
Now that you’re familiar with the applications of Knapsack Problem, let’s explore how upGrad can take your learning journey forward.
Now that you have a clear understanding of data modeling for data governance, you can deepen your expertise with upGrad’s certification courses. These courses will teach you advanced techniques in data governance, compliance management, and security strategies, helping you unlock the full potential of your data.
Through hands-on projects, you’ll apply these principles to real-world scenarios, ensuring robust data governance and securing your data assets.
Here are some relevant courses you can explore:
If you're unsure about the next step in your learning journey, you can contact upGrad’s personalized career counseling for guidance on choosing the best path tailored to your goals. You can also visit your nearest upGrad center and start hands-on training today!
Boost your career with our popular Software Engineering courses, offering hands-on training and expert guidance to turn you into a skilled software developer.
Master in-demand Software Development skills like coding, system design, DevOps, and agile methodologies to excel in today’s competitive tech industry.
Stay informed with our widely-read Software Development articles, covering everything from coding techniques to the latest advancements in software engineering.
231 articles published
Get Free Consultation
By submitting, I accept the T&C and
Privacy Policy
India’s #1 Tech University
Executive PG Certification in AI-Powered Full Stack Development
77%
seats filled
Top Resources