Skip to main content

0-1 knapsack in Dynamic Programming

DP Tutorial 1-
0-1            Knapsack dynamic programming-

Problem Explanation-

you are given a weight array and respective value array and maximum size of knapsack and you have to put these item in such a way so that you will get maximum total value in knapsack.

 

Type of knapsack problem

1.Fractional Knapsack-

This type of problem lie under the category of greedy .For more details -https://www.geeksforgeeks.org/fractional-knapsack-problem/

2.0-1 knapsack

This is a dp based problem.As 1 means you take this item in knapsack 0 means you didn’t take this item in knapsack.

3.Unbounded knapsack

The difference between 0-1 and unbounded knapsack is that you have infinity supply of each item.

 

How to identify Dynamic Programming-

From tutorial 0 we know that you have to find two things

1.Choice-

As in  this problem you can take item or not .

2.Optimal-

Means maximum or minimum and here you have to find maximum profit.

Choice Diagram- I recommend you to always make choice diagram this will help you to visualize and writing recursion.

 

Solution Using Recursion-

Function()

{

    Base condition;

     Choice diagram;
}

 

How to think about base condition?

Think about smallest valid input.

1.Array size can be zero

2.Size of knapsack can be zero

So base condition

If(n==0||W==0)

 return 0;

 

Code for choice diagram

 

Taken then=> value[n-1]+knapsack(value[],weight[],n-1,W-weight[n-1])

Not Taken=>knapsack(value[],weight[],n-1,W)

Size greater =>knapsack(value[],weight[],n-1,W)

 

Code-

 int knapsack(int value[],int weight[],int n,int W)

{

if(n==0||W==0)

return 0;

if(weight[n-1]<=W)

return max(value[n-1]+knapsack(value,weight,n-1,W-weight[n-1]),

knapsack(value,weight,n-1,W));

else

return knapsack(value,weight,n-1,W);

}

Solution Using Memoization-

In memorization or bottom up to avoid recalculation we saved the calculation in a array .

But what is the size of array ?

We simply convert recursion recurrence relation to memorization

What value change

1.n and 2.W (size of Knapsack)

Now array will be dp[n][W]

We initially filled array to -1 to check it if here in this point calculation is done or not;

Code-

int knapsack(int value[],int weight[],int n,int W)
{   if(dp[n][W]!=-1)
       return dp[n][W];
if(n==0||W==0)
return 0;
if(weight[n-1]<=W)
return dp[n][W]=max(value[n-1]+knapsack(value,weight,n-1,W-weight[n-1]),
knapsack(value,weight,n-1,W));
else
return dp[n][W]=knapsack(value,weight,n-1,W);
}

 

Child Problems-

1.subset sum

2.Equal Sum Partition

3.Count of Subset sum

4.minimum Subset sum Difference

5.Target Sum

6.No. of subset equal to given difference

 

Where to Practice-

https://practice.geeksforgeeks.org/problems/0-1-knapsack-problem/0

 

Code for above problem (complete code)

#include <bits/stdc++.h>
using namespace std;
int dp[1001][1001];
int knapsack(int value[],int weight[],int n,int W)
{   if(dp[n][W]!=-1)
       return dp[n][W];
if(n==0||W==0)
return 0;
if(weight[n-1]<=W)
return dp[n][W]=max(value[n-1]+knapsack(value,weight,n-1,W-weight[n-1]),
knapsack(value,weight,n-1,W));
else
return dp[n][W]=knapsack(value,weight,n-1,W);
}
int main() {
int t;
cin>>t;
while(t--)
{
    int n,W;cin>>n>>W;
    int value[n+1],weight[n+1];
    memset(dp,-1,sizeof(dp));
    for(int i=0;i<n;i++)
     cin>>value[i];
    
    for(int i=0;i<n;i++)
      cin>>weight[i];
    cout<<knapsack(value,weight,n,W)<<"\n";
}
}

Comments

Popular posts from this blog

Write a code simulating ARP /RARP protocols

   Write a code simulating ARP /RARP protocols . Aim:        To write a java program for simulating ARP/RARP protocols ALGORITHM: server 1. Create a server socket and bind it to port. 2. Listen for new connection and when a connection arrives, accept it. 3. Send server ‟ s date and time to the client. 4. Read client ‟ s IP address sent by the client. 5. Display the client details. 6. Repeat steps 2-5 until the server is terminated. 7. Close all streams. 8. Close the server socket. 9. Stop. Client 1. Create a client socket and connect it to the server ‟ s port number. 2. Retrieve its own IP address using built-in function. 3. Send its address to the server. 4. Display the date & time sent by the server. 5. Close the input and output streams. 6. Close the client socket. 7. Stop. Program Program for Address Resolutuion Protocol (ARP) using TCP Client: import java.io.*; import java.net.*; impor...

The Future of Web Development: Why Next.js is Going Viral

  Are you ready to level up your web development game? Look no further than Next.js, the latest sensation in the world of web development that's taking the industry by storm. With its powerful features, flexibility, and performance optimizations, Next.js is becoming the go-to framework for building modern web applications. In this blog post, we'll explore why Next.js is going viral and how it's changing the landscape of web development. Supercharged Performance: One of the main reasons why Next.js is making waves is its superior performance capabilities. With built-in optimizations like automatic static site generation (SSG) and server-side rendering (SSR), Next.js allows you to create blazing-fast web applications that load quickly and deliver seamless user experiences. This is especially important in today's fast-paced digital world, where users demand instant gratification and have little patience for slow-loading websites. Flexibility and Scalability: Next.js provid...

Importants Links of Leetcode

  Here are all the important discussion posts which contain brief descriptions about a topic with its problem list. Recursion:- A.   https://leetcode.com/tag/recursion/discuss/1733447/Become-Master-In-Recursion Binary Tree and Binary Search Tree:- A.   https://leetcode.com/tag/binary-tree/discuss/1212004/Binary-Trees-study-guide B.   https://leetcode.com/tag/binary-tree/discuss/1820334/Become-Master-in-Tree C.   https://leetcode.com/tag/binary-tree/discuss/1094690/Views-and-Traversal-of-binary-tree-or-Important-topics-or-Must-Read-%3A- ) Dynamic Programming:- A.   https://leetcode.com/discuss/study-guide/458695/Dynamic-Programming-Patterns B.   https://leetcode.com/tag/dynamic-programming/discuss/1437879/Dynamic-Programming-Patterns C.   https://leetcode.com/tag/dynamic-programming/discuss/662866/DP-for-Beginners-Problems-or-Patterns-or-Sample-Solutions D.   https://leetcode.com/tag/dynamic-programming/discuss/1050391/Must-do-Dynamic-programm...