Explore Courses
Liverpool Business SchoolLiverpool Business SchoolMBA by Liverpool Business School
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA (Master of Business Administration)
  • 15 Months
Popular
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Business Administration (MBA)
  • 12 Months
New
Birla Institute of Management Technology Birla Institute of Management Technology Post Graduate Diploma in Management (BIMTECH)
  • 24 Months
Liverpool John Moores UniversityLiverpool John Moores UniversityMS in Data Science
  • 18 Months
Popular
IIIT BangaloreIIIT BangalorePost Graduate Programme in Data Science & AI (Executive)
  • 12 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
upGradupGradData Science Bootcamp with AI
  • 6 Months
New
University of MarylandIIIT BangalorePost Graduate Certificate in Data Science & AI (Executive)
  • 8-8.5 Months
upGradupGradData Science Bootcamp with AI
  • 6 months
Popular
upGrad KnowledgeHutupGrad KnowledgeHutData Engineer Bootcamp
  • Self-Paced
upGradupGradCertificate Course in Business Analytics & Consulting in association with PwC India
  • 06 Months
OP Jindal Global UniversityOP Jindal Global UniversityMaster of Design in User Experience Design
  • 12 Months
Popular
WoolfWoolfMaster of Science in Computer Science
  • 18 Months
New
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Rushford, GenevaRushford Business SchoolDBA Doctorate in Technology (Computer Science)
  • 36 Months
IIIT BangaloreIIIT BangaloreCloud Computing and DevOps Program (Executive)
  • 8 Months
New
upGrad KnowledgeHutupGrad KnowledgeHutAWS Solutions Architect Certification
  • 32 Hours
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Popular
upGradupGradUI/UX Bootcamp
  • 3 Months
upGradupGradCloud Computing Bootcamp
  • 7.5 Months
Golden Gate University Golden Gate University Doctor of Business Administration in Digital Leadership
  • 36 Months
New
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Golden Gate University Golden Gate University Doctor of Business Administration (DBA)
  • 36 Months
Bestseller
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDoctorate of Business Administration (DBA)
  • 36 Months
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (DBA)
  • 36 Months
KnowledgeHut upGradKnowledgeHut upGradSAFe® 6.0 Certified ScrumMaster (SSM) Training
  • Self-Paced
KnowledgeHut upGradKnowledgeHut upGradPMP® certification
  • Self-Paced
IIM KozhikodeIIM KozhikodeProfessional Certification in HR Management and Analytics
  • 6 Months
Bestseller
Duke CEDuke CEPost Graduate Certificate in Product Management
  • 4-8 Months
Bestseller
upGrad KnowledgeHutupGrad KnowledgeHutLeading SAFe® 6.0 Certification
  • 16 Hours
Popular
upGrad KnowledgeHutupGrad KnowledgeHutCertified ScrumMaster®(CSM) Training
  • 16 Hours
Bestseller
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 4 Months
upGrad KnowledgeHutupGrad KnowledgeHutSAFe® 6.0 POPM Certification
  • 16 Hours
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Science in Artificial Intelligence and Data Science
  • 12 Months
Bestseller
Liverpool John Moores University Liverpool John Moores University MS in Machine Learning & AI
  • 18 Months
Popular
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
IIIT BangaloreIIIT BangaloreExecutive Post Graduate Programme in Machine Learning & AI
  • 13 Months
Bestseller
IIITBIIITBExecutive Program in Generative AI for Leaders
  • 4 Months
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
IIIT BangaloreIIIT BangalorePost Graduate Certificate in Machine Learning & Deep Learning (Executive)
  • 8 Months
Bestseller
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Liverpool Business SchoolLiverpool Business SchoolMBA with Marketing Concentration
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA with Marketing Concentration
  • 15 Months
Popular
MICAMICAAdvanced Certificate in Digital Marketing and Communication
  • 6 Months
Bestseller
MICAMICAAdvanced Certificate in Brand Communication Management
  • 5 Months
Popular
upGradupGradDigital Marketing Accelerator Program
  • 05 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Corporate & Financial Law
  • 12 Months
Bestseller
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in AI and Emerging Technologies (Blended Learning Program)
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Intellectual Property & Technology Law
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Dispute Resolution
  • 12 Months
upGradupGradContract Law Certificate Program
  • Self paced
New
ESGCI, ParisESGCI, ParisDoctorate of Business Administration (DBA) from ESGCI, Paris
  • 36 Months
Golden Gate University Golden Gate University Doctor of Business Administration From Golden Gate University, San Francisco
  • 36 Months
Rushford Business SchoolRushford Business SchoolDoctor of Business Administration from Rushford Business School, Switzerland)
  • 36 Months
Edgewood CollegeEdgewood CollegeDoctorate of Business Administration from Edgewood College
  • 24 Months
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with Concentration in Generative AI
  • 36 Months
Golden Gate University Golden Gate University DBA in Digital Leadership from Golden Gate University, San Francisco
  • 36 Months
Liverpool Business SchoolLiverpool Business SchoolMBA by Liverpool Business School
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA (Master of Business Administration)
  • 15 Months
Popular
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Business Administration (MBA)
  • 12 Months
New
Deakin Business School and Institute of Management Technology, GhaziabadDeakin Business School and IMT, GhaziabadMBA (Master of Business Administration)
  • 12 Months
Liverpool John Moores UniversityLiverpool John Moores UniversityMS in Data Science
  • 18 Months
Bestseller
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Science in Artificial Intelligence and Data Science
  • 12 Months
Bestseller
IIIT BangaloreIIIT BangalorePost Graduate Programme in Data Science (Executive)
  • 12 Months
Bestseller
O.P.Jindal Global UniversityO.P.Jindal Global UniversityO.P.Jindal Global University
  • 12 Months
WoolfWoolfMaster of Science in Computer Science
  • 18 Months
New
Liverpool John Moores University Liverpool John Moores University MS in Machine Learning & AI
  • 18 Months
Popular
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (AI/ML)
  • 36 Months
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDBA Specialisation in AI & ML
  • 36 Months
Golden Gate University Golden Gate University Doctor of Business Administration (DBA)
  • 36 Months
Bestseller
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDoctorate of Business Administration (DBA)
  • 36 Months
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (DBA)
  • 36 Months
Liverpool Business SchoolLiverpool Business SchoolMBA with Marketing Concentration
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA with Marketing Concentration
  • 15 Months
Popular
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Corporate & Financial Law
  • 12 Months
Bestseller
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Intellectual Property & Technology Law
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Dispute Resolution
  • 12 Months
IIITBIIITBExecutive Program in Generative AI for Leaders
  • 4 Months
New
IIIT BangaloreIIIT BangaloreExecutive Post Graduate Programme in Machine Learning & AI
  • 13 Months
Bestseller
upGradupGradData Science Bootcamp with AI
  • 6 Months
New
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
KnowledgeHut upGradKnowledgeHut upGradSAFe® 6.0 Certified ScrumMaster (SSM) Training
  • Self-Paced
upGrad KnowledgeHutupGrad KnowledgeHutCertified ScrumMaster®(CSM) Training
  • 16 Hours
upGrad KnowledgeHutupGrad KnowledgeHutLeading SAFe® 6.0 Certification
  • 16 Hours
KnowledgeHut upGradKnowledgeHut upGradPMP® certification
  • Self-Paced
upGrad KnowledgeHutupGrad KnowledgeHutAWS Solutions Architect Certification
  • 32 Hours
upGrad KnowledgeHutupGrad KnowledgeHutAzure Administrator Certification (AZ-104)
  • 24 Hours
KnowledgeHut upGradKnowledgeHut upGradAWS Cloud Practioner Essentials Certification
  • 1 Week
KnowledgeHut upGradKnowledgeHut upGradAzure Data Engineering Training (DP-203)
  • 1 Week
MICAMICAAdvanced Certificate in Digital Marketing and Communication
  • 6 Months
Bestseller
MICAMICAAdvanced Certificate in Brand Communication Management
  • 5 Months
Popular
IIM KozhikodeIIM KozhikodeProfessional Certification in HR Management and Analytics
  • 6 Months
Bestseller
Duke CEDuke CEPost Graduate Certificate in Product Management
  • 4-8 Months
Bestseller
Loyola Institute of Business Administration (LIBA)Loyola Institute of Business Administration (LIBA)Executive PG Programme in Human Resource Management
  • 11 Months
Popular
Goa Institute of ManagementGoa Institute of ManagementExecutive PG Program in Healthcare Management
  • 11 Months
IMT GhaziabadIMT GhaziabadAdvanced General Management Program
  • 11 Months
Golden Gate UniversityGolden Gate UniversityProfessional Certificate in Global Business Management
  • 6-8 Months
upGradupGradContract Law Certificate Program
  • Self paced
New
IU, GermanyIU, GermanyMaster of Business Administration (90 ECTS)
  • 18 Months
Bestseller
IU, GermanyIU, GermanyMaster in International Management (120 ECTS)
  • 24 Months
Popular
IU, GermanyIU, GermanyB.Sc. Computer Science (180 ECTS)
  • 36 Months
Clark UniversityClark UniversityMaster of Business Administration
  • 23 Months
New
Golden Gate UniversityGolden Gate UniversityMaster of Business Administration
  • 20 Months
Clark University, USClark University, USMS in Project Management
  • 20 Months
New
Edgewood CollegeEdgewood CollegeMaster of Business Administration
  • 23 Months
The American Business SchoolThe American Business SchoolMBA with specialization
  • 23 Months
New
Aivancity ParisAivancity ParisMSc Artificial Intelligence Engineering
  • 24 Months
Aivancity ParisAivancity ParisMSc Data Engineering
  • 24 Months
The American Business SchoolThe American Business SchoolMBA with specialization
  • 23 Months
New
Aivancity ParisAivancity ParisMSc Artificial Intelligence Engineering
  • 24 Months
Aivancity ParisAivancity ParisMSc Data Engineering
  • 24 Months
upGradupGradData Science Bootcamp with AI
  • 6 Months
Popular
upGrad KnowledgeHutupGrad KnowledgeHutData Engineer Bootcamp
  • Self-Paced
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Bestseller
upGradupGradUI/UX Bootcamp
  • 3 Months
upGradupGradCloud Computing Bootcamp
  • 7.5 Months
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 5 Months
upGrad KnowledgeHutupGrad KnowledgeHutSAFe® 6.0 POPM Certification
  • 16 Hours
upGradupGradDigital Marketing Accelerator Program
  • 05 Months
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
upGradupGradData Science Bootcamp with AI
  • 6 Months
Popular
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Bestseller
upGradupGradUI/UX Bootcamp
  • 3 Months
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 4 Months
upGradupGradCertificate Course in Business Analytics & Consulting in association with PwC India
  • 06 Months
upGradupGradDigital Marketing Accelerator Program
  • 05 Months

Understanding and Implementing the Knapsack Problem (0/1)

By Mukesh Kumar

Updated on Mar 20, 2025 | 24 min read | 1.1k views

Share:

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. 

Understanding the Knapsack Problem

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:

  • Each item has a value and a weight.
  • There's a maximum weight limit for the knapsack.
  • The goal is to maximize the total value without exceeding the weight limit.
  • Each item is either included or excluded (0/1).
  • It is useful in resource allocation, budgeting, cargo loading, and more.
  • The 0/1 Knapsack Problem is NP-complete, meaning it’s computationally difficult to solve for large inputs, as the time required to find the optimal solution grows exponentially. 

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:

  • Weight: The item's weight.
  • Profit: The item's profit or value.

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:

  • Item 1: Weight = 4 units, Profit = 1
  • Item 2: Weight = 5 units, Profit = 2
  • Item 3: Weight = 1 unit, Profit = 3

Analysis:

  • Item 1 alone fills the knapsack to its capacity, yielding a profit of 1.
  • Item 3 fits comfortably within the capacity and offers a higher profit of 3.

Therefore, the optimal solution is to select Item 3, resulting in a maximum profit of 3.

Key Considerations:

  • Item Selection: Each item is indivisible; you must decide to include it entirely or exclude it.
  • Capacity Constraint: The total weight of selected items must not exceed the knapsack's capacity.
  • Profit Maximization: Aim to achieve the highest possible profit within the given constraints.

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.

Coverage of AWS, Microsoft Azure and GCP services

Certification8 Months
View Program

Job-Linked Program

Bootcamp36 Weeks
View Program

When optimizing decisions under constraints, it’s essential to understand dynamic programming for solving the Knapsack Problem. upGrad’s online Software Development courses can help you master problem-solving techniques, including optimization algorithms to tackle real-world challenges.

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: A Step-by-Step Example

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:

  • Item 1: Weight = 2, Value = 3
  • Item 2: Weight = 3, Value = 4
  • Item 3: Weight = 4, Value = 5

The capacity of the knapsack is 5 units.

Step 1: Define the Input

  • Weights: [2, 3, 4]
  • Values: [3, 4, 5]
  • Knapsack Capacity: 5

You need to choose a combination of these items to maximize the value of the knapsack without exceeding the weight limit.

Step 2: Initialize the Dynamic Programming Table

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

Step 3: Populate the DP Table

Now, let's go through each item and each possible capacity to fill up the table.

For Item 1 (Weight = 2, Value = 3):

  • For capacities j = 1, we cannot include Item 1, so the value stays 0.
  • For capacities j = 2 and above, we can include Item 1. The value becomes 3 (since Item 1 fits into the knapsack at capacity 2).

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):

  • For capacities j = 1 and j = 2, we cannot include Item 2, so the value remains unchanged from the previous row.
  • For capacity j = 3 and above, we can either include Item 2 or not. Including Item 2 gives a total value of 4, which is higher than the value of 3 (from Item 1 alone).

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):

  • For capacities j = 1, j = 2, and j = 3, we cannot include Item 3, so the value remains unchanged from the previous row.
  • For capacity j = 4 and j = 5, including Item 3 results in a higher value than not including it.

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

Step 4: Final Solution

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.

Step 5: Trace the Solution (Optional)

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.

  • The value at dp[2][5] (which is 7) is greater than dp[1][5]. This means Item 2 was included.
  • The remaining capacity is 2 (5 - 3 = 2), and Item 1 is included because the value at dp[1][2] is 3.

Thus, the selected items are:

  • Item 1 (Weight = 2, Value = 3)
  • Item 2 (Weight = 3, Value = 4)

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. 

Knapsack Problem Variants and Optimizations

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:

1. 0-1 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:

  • Exclude the item: Use the value from the previous item.
  • Include the item: Add the value of the item and reduce the capacity.

Transition Equation:

f[j] = max(f[j], f[j - w[i]] + v[i])

Implementation:

  • Time Complexity: O(n * W)
  • Space Complexity: O(W)

2. Complete Knapsack Problem

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:

  • Time Complexity: O(n * W)
  • Space Complexity: O(W)

3. Multiple Knapsack Problem

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:

  • O(W * sum(k_i)), where k_i is the number of available items for each type.

4. Binary Grouping Optimization (Multiple Knapsack)

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:

  • O(W * sum(log(k_i))).

5. Monotone Queue Optimization

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).

6. Mixed Knapsack Problem

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.

Different Approaches to Solving the 0/1 Knapsack Problem

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:

Approach 1: Naive Recursive Solution

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:

  • The function knapsackRec is defined to take the current capacity W, vectors of profits val and weights wt, and the number of items n.
  • The base case checks if there are no items left or if the capacity is zero, returning a profit of zero.
  • If the weight of the current item exceeds the remaining capacity, it cannot be included, so the function recurses without including it.
  • Otherwise, the function calculates the profit for both including and excluding the current item, and returns the maximum of the two.

Output:

Maximum Profit: 3

Also Read: Learn Naive Bayes Algorithm For Machine Learning [With Examples]

Approach 2: Top-Down Dynamic Programming (Memoization)

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:

  • The function knapsackRec now takes an additional parameter memo, a 2D vector initialized with -1 to indicate uncomputed subproblems.
  • Before performing any calculations, the function checks if the result for the current subproblem has already been computed; if so, it returns the stored value.
  • This ensures that each subproblem is solved only once, significantly reducing the number of computations.

Output:

Maximum Profit: 3

Approach 3: Bottom-Up Dynamic Programming (Tabulation)

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:

  • The table dp is initialized with zeros. The first row and column represent the base cases where either there are no items or the capacity is zero, resulting in a profit of zero.
  • As the table is filled, each cell represents the best solution for a subproblem, either including or excluding an item.
  • The final solution is found in the bottom-right cell of the table, dp[n][W], which holds the maximum profit that can be obtained with the given knapsack capacity.

Output:

Maximum Profit: 3

Approach 4: Space-Optimized Dynamic Programming

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:

  • The 1D array dp is initialized with zeros. Initially, the maximum profit for every possible weight capacity is zero.
  • The loop traverses the dp array from right to left. By doing so, we ensure that the calculation for a particular weight capacity does not overwrite the results from the same iteration.
  • The final value of dp[W] holds the maximum possible profit for the given knapsack capacity.

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

Fractional Knapsack Problem: Greedy Approach

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:

  • For each item, calculate the ratio: profit/weight.
  • Sort the items in decreasing order of the profit/weight ratio.
  • Start adding items from the sorted list. If the item fits in the remaining capacity, add it fully.
  • If an item doesn’t fit, take as much as possible (i.e., a fraction).
  • Continue until the knapsack is full or all items are considered.

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:

  • You define a structure Item that holds the profit and weight of each item.
  • The cmp function sorts items based on their profit/weight ratio in descending order.
  • In the fractionalKnapsack function, you sort the items and then iterate over them. 
  • For each item: If it fits in the knapsack, you add its full profit. If it doesn't fit, you add a fraction of its profit (based on the remaining capacity).
  • The function returns the total maximum profit that can be obtained with the given capacity.

Example 1

1. Input:

  • Items: {{60, 10}, {100, 20}, {120, 30}}
  • Knapsack Capacity (W): 50

2. Calculate Profit/Weight Ratios:

  • Item 1: 60/10 = 6
  • Item 2: 100/20 = 5
  • Item 3: 120/30 = 4

3. Sort Items by Ratio:

  • Sorted items: {{60, 10}, {100, 20}, {120, 30}}

4. Knapsack Filling:

  • Item 1 fits: Profit = 60, Remaining Capacity = 50 - 10 = 40
  • Item 2 fits: Profit = 60 + 100 = 160, Remaining Capacity = 40 - 20 = 20
  • Item 3: Only part of it fits (20/30 fraction), Profit from Item 3 = (20/30) * 120 = 80. Total Profit = 160 + 80 = 240.

Output:

Maximum Profit: 240

Example 2:

1. Input:

  • Items: {{500, 30}}
  • Knapsack Capacity (W): 10

2. Calculate Profit/Weight Ratio:

  • Item 1: 500/30 ≈ 16.67

3. Sort Items by Ratio:

  • Sorted items: {{500, 30}}

4. Knapsack Filling:

  • Only a fraction of Item 1 fits (10/30 fraction), Profit = (10/30) * 500 = 166.67.

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.

Real-World Applications of 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. 

How Can upGrad Enhance Your Programming Skills?

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:

  • Java Object-oriented Programming
  • JavaScript Basics from Scratch
  • Master of Science in AI and Data Science
  • Best Full Stack Developer Bootcamp
  • Master of Design in User Experience

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.

Frequently Asked Questions (FAQs)

1. How is the Knapsack Problem used in cloud resource optimization?

2. Can the Knapsack Problem be applied in dynamic pricing strategies?

3. How can the Knapsack Problem help with personalized marketing campaigns?

4. How do you deal with time-dependent constraints in real-world Knapsack Problems?

5. What role does the Knapsack Problem play in optimizing warehouse storage?

6. How is the Knapsack Problem applied to optimize employee scheduling in HR?

7. How does the Knapsack Problem assist in optimizing resource allocation for event planning?

8. What challenges are faced when adapting the Knapsack Problem to real-time supply chain decisions?

9. How can the Knapsack Problem be used for fleet management in transportation?

10. What are the limitations of applying the Knapsack Problem in multi-stage project management?

11. Can the Knapsack Problem be useful in designing sustainable energy systems?

Mukesh Kumar

137 articles published

Get Free Consultation

+91

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

View Program

Top Resources

Recommended Programs

upGrad

AWS | upGrad KnowledgeHut

AWS Certified Solutions Architect - Associate Training (SAA-C03)

69 Cloud Lab Simulations

Certification

32-Hr Training by Dustin Brimberry

View Program
upGrad

Microsoft | upGrad KnowledgeHut

Microsoft Azure Data Engineering Certification

Access Digital Learning Library

Certification

45 Hrs Live Expert-Led Training

View Program
upGrad

upGrad KnowledgeHut

Professional Certificate Program in UI/UX Design & Design Thinking

#1 Course for UI/UX Designers

Bootcamp

3 Months

View Program

Suggested Blogs

blog-card

Uses of C Language - Its Relevance in 2025

C is a powerful, general-purpose programming language known for its speed, efficiency, and control over system resources. It forms the foundation of many modern languages like 

21 Mar 2025 | 11 min read

blog-card

Doubly Linked List Implementation in C and Java: A Comprehensive Guide

Doubly Linked Lists are a key data structure in computer science, helping solve problems that require efficient insertion and deletion operations. Unlike singly linked lists, a doubly linked list allows traversal in both directions, making it more versatile in scenarios where both forward and backward navigation are needed.

20 Mar 2025 | 21 min read

blog-card

SQL Jobs for Freshers: Salary, Career Growth & Opportunities

Imagine data as a vast lake behind a dam. Just as an engineer carefully controls the flow of water to ensure optimal flow, an SQL developer manages the “vast lake” of data. They ensure that the data is stored safely and released at the right time so businesses can make informed decisions without being underprepared.  T

19 Mar 2025 | 14 min read

blog-card

Java Developer Salary: What to Expect in India 2025

Java developers play a crucial role in modern organizations by creating scalable and secure applications that power essential digital infrastructure. Their expertise is central to designing robust backend systems, optimizing code performance, and ensuring the reliability of software used by businesses worldwide. The importa

19 Mar 2025 | 6 min read