ProDeveloperTutorial.com

Tutorials and Programming Solutions
Menu
  • Shell Scripting
  • System Design
  • Linux System Programming
  • 4g LTE
  • Coding questions
  • C
  • C++
  • DSA
  • GIT
  • 450 DSA Cracker
  • 5G NR
  • O-RAN

Knapsack Problem tutorial 2: 0/1 knapsack problem tutorial with implementation

prodevelopertutorial August 18, 2019

In the previous chapter we have solved fractional knapsack problem. In this chapter we shall solve 0/1 knapsack problem.

Problem Statement:

You are given ‘n’ number of object with their weights and profits.

 

You are given a bag with max capacity it can hold. Objective here is to fill the bag/knapsack so that you get max profit.

As this is 0/1 knapsack problem, you can either take the whole object or don’t take the object at all.

 

We can solve this problem with help of Dynamic Programming. We cannot solve it with help of greedy approach.

 

 0/1 knapsack problem tutorial with implementation

 

Before we solve using DP, we shall see how to solve it with help of brute force approach.

 

In brute force approach, we take an array of size ‘n’, then mark the objects as 1, if we select it.

 

For example:

 

We have 4 objects and hence we take an array of size 4 and initialize it to 0.

[0, 0, 0, 0]

 

If we user the object 1 and 4, we make them as 1 and calculate the profit.

[1, 0, 0, 1] the total weight will be 2 + 3 = 5 and profit will be 4 + 4 =8.

 

Similarly, we do all the combinations and check the profit whose weight is less than or equal to 8. Then select the max profit.

 

This will take 2^n time and is not optimal.

 

Hence we shall use Dynamic Programming to solve the problem.

 

As always in DP, we first write our DP table:

 

 0/1 knapsack problem tutorial with implementation

 

In the above table, we can see that, in the row we have taken individual weights. In the column, we have taken the weights of item in increasing order [ascending].

 

In the DP table we fill with the profit value for the selected item.

 

So, when the total weight is 0, the profit will also be 0. SO we shall fill our table as below:

 

 0/1 knapsack problem tutorial with implementation

 

Now, we have chosen an item with weight 2. So till weight 2, the profit will be 0. And after weight 2, the profit will be ‘4’. Because ‘4’ is the profit for 2.

 

As we have only 1 item with weight 2, the profit for all the items will be 4.

The updated DP table is as below:

 

 0/1 knapsack problem tutorial with implementation

 

Now we have weights [2, 3]. So till weight 2, we copy the values from above table.

 

Now when we arrive at weight 3, we have 2 choices. Either choose weight 2 with profit 4 or weight 3 with profit 4. As both of the profits are same, we can either choose object with weight 2 or object with weight 3.

 0/1 knapsack problem tutorial with implementation

 

Now at weight 4, the profit will remain the same

 

But at weight 5, we can choose both objects with weight 2 and object with weight 3. So the total profit will be 8. It will be continued till weight 7.

 0/1 knapsack problem tutorial with implementation

 

From the above table, can we make out a formula to fill the values in the table?

 

Yes, below is the formula:

max [ [i-1, j], [value_at_i + [i-1, j-weight] ] ]

Implementation of 0/1 knapsack problem using C++

#include <iostream>

using namespace std;

int max(int a, int b)  
{
    return (a > b) ? a : b;
}

int knapSack(int knapsack_size, int weight[], int object[], int n)
{
    int i, w;
    int DP[n + 1][knapsack_size + 1];

    for(i = 0; i <= n; i++)
    {
        for(w = 0; w <= knapsack_size; w++)
        {
            if(i == 0 || w == 0)
               DP[i][w] = 0;
            else if(weight[i - 1] <= w)
              DP[i][w] = max(object[i - 1] + DP[i - 1][w - weight[i - 1]], DP[i - 1][w]);
            else
              DP[i][w] = DP[i - 1][w];
        }
    }

    return DP[n][knapsack_size];
}


int main()
{
    int object[] = {2, 6, 7, 3};
    int weight[] = {4, 3, 2, 4};
    int knapsack_size = 8;
    int n = sizeof(weight) / sizeof(weight[0]);

    cout << "The solution for knapsack 0/1 is = "<< knapSack(knapsack_size, weight, object, n)<<endl;
    return 0;
}

 

Output:

The solution for knapsack 0/1 is = 13

 

Further Reading:

AJ’s definitive guide for DS and Algorithms. Click here to study the complete list of algorithm and data structure tutorial. 85+ chapters to study from.

 

List Of Tutorials available in this website:

C Programming 20+ ChaptersC++ Programming 80+ Chapters
100+ Solved Coding QuestionsData Structures and Algorithms 85+ Chapters
System design 20+ ChaptersShell Scripting 12 Chapters
4g LTE 60+ ChaptersMost Frequently asked Coding questions
5G NR 50+ ChaptersLinux System Programming 20+ chapters
Share
Email
Tweet
Linkedin
Reddit
Stumble
Pinterest
Prev Article
Next Article

About The Author

prodevelopertutorial

Follow this blog to learn more about C, C++, Linux, Competitive Programming concepts, Data Structures.

Leave a Reply Cancel Reply

You must be logged in to post a comment.

ProDeveloperTutorial.com

Tutorials and Programming Solutions
Copyright © 2023 ProDeveloperTutorial.com
We use cookies on our website to give you the most relevant experience by remembering your preferences and repeat visits. By clicking “Accept”, you consent to the use of ALL the cookies.
Do not sell my personal information.
Cookie SettingsAccept
Manage consent

Privacy Overview

This website uses cookies to improve your experience while you navigate through the website. Out of these, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may affect your browsing experience.
Necessary
Always Enabled
Necessary cookies are absolutely essential for the website to function properly. These cookies ensure basic functionalities and security features of the website, anonymously.
CookieDurationDescription
cookielawinfo-checkbox-analytics11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Analytics".
cookielawinfo-checkbox-functional11 monthsThe cookie is set by GDPR cookie consent to record the user consent for the cookies in the category "Functional".
cookielawinfo-checkbox-necessary11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookies is used to store the user consent for the cookies in the category "Necessary".
cookielawinfo-checkbox-others11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Other.
cookielawinfo-checkbox-performance11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Performance".
viewed_cookie_policy11 monthsThe cookie is set by the GDPR Cookie Consent plugin and is used to store whether or not user has consented to the use of cookies. It does not store any personal data.
Functional
Functional cookies help to perform certain functionalities like sharing the content of the website on social media platforms, collect feedbacks, and other third-party features.
Performance
Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.
Analytics
Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics the number of visitors, bounce rate, traffic source, etc.
Advertisement
Advertisement cookies are used to provide visitors with relevant ads and marketing campaigns. These cookies track visitors across websites and collect information to provide customized ads.
Others
Other uncategorized cookies are those that are being analyzed and have not been classified into a category as yet.
SAVE & ACCEPT