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

Create a socket for HTTP for web page upload and download

Create a socket for HTTP for web page upload and download. Aim: To write a java program for socket for HTTP for web page upload and download . Algorithm 1.Start the program. 2.Get the frame size from the user 3.To create the frame based on the user request. 4.To send frames to server from the client side. 5.If your frames reach the server it will send ACK signal to client otherwise it will send NACK signal to client. 6.Stop the program Program : Client import javax.swing.*; import java.net.*; import java.awt.image.*; import javax.imageio.*; import java.io.*; import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; public class Client{ public static void main(String args[]) throws Exception{ Socket soc; BufferedImage img = null; soc=new Socket("localhost",4000); System.out.println("Client is running. ");  try { System.out.println("Reading image from disk. "); im...

Write an HTML program to design an entry form of student details and send it to store at database server like SQL, Oracle or MS Access

Write an HTML program to design an entry form of student details and send it to store at database server like SQL, Oracle or MS Access <!DOCTYPE html> <html> <head> <title>PHP insertion</title> <link href="css/insert.css" rel="stylesheet"> </head> <body> <div class="maindiv"> <!--HTML Form --> <div class="form_div"> <div class="title"> <h2>Insert Data In Database Using PHP.</h2> </div> <form action="insert.php" method="post"> <!-- Method can be set as POST for hiding values in URL--> <h2>Form</h2> <label>Name:</label> <input class="input" name="name" type="text" value=""> <label>Email:</label> <input class="input" name="email" type="text" value=""> <label>Contact:</label> <inp...

Write a code simulating PING and TRACEROUTE commands

  Write a code simulating PING command     Aim:   To Write the java program for simulating ping command   Algorithm Step 1: start the program. Step 2: Include necessary package in java. Step 3: To create a process object p to implement the ping command. Step 4: declare one BufferedReader stream class object. Step 5: Get thedetails of the server          5.1: length of the IP address.          5.2: time required to get the details.          5.3: send packets , receive packets and lost packets.          5.4: minimum ,maximum and average times. Step 6: print the results. Step 7:Stop the program.   Program:   import java.io.*; import java.net.*; class pingserver { public static void main(String args[]) { try { String str; System.out.print(" Enter...