ONLINE SUMMER TRAINING Online Courses Free Tutorials 
 Placement Preparation 
Artificial Intelligence(AI) & Machine Learning(ML) Training in Jaipur
0 like 0 dislike
176 views
in VTU B.Tech (CSE-IV Sem) Design and Analysis of Algorithm Lab by Goeduhub's Expert (5.8k points)

0/1 Knapsack problem using Greedy Method

Goeduhub's Online Courses @Udemy

For Indian Students- INR 570/- || For International Students- $12.99/-

S.No.

Course Name

Apply Coupon

1.

Tensorflow 2 & Keras:Deep Learning & Artificial Intelligence

Apply Coupon

2.

Computer Vision with OpenCV | Deep Learning CNN Projects

Apply Coupon

3.

Complete Machine Learning & Data Science with Python Apply Coupon

4.

Natural Language Processing-NLP with Deep Learning in Python Apply Coupon

5.

Computer Vision OpenCV Python | YOLO| Deep Learning in Colab Apply Coupon

6.

Complete Python Programming from scratch with Projects Apply Coupon

1 Answer

0 like 0 dislike
by Goeduhub's Expert (5.8k points)
 
Best answer

For Theory of Knapsack Problem using Greedy Approach Click here

Java Program

import java.util.Scanner;

public class Knap2

{

public static void main(String[] args) 

{

int i,j=0,max_qty,m,n;

float sum=0,max;

Scanner sc = new Scanner(System.in);

int array[][]=new int[2][20];

System.out.print("Enter no of items: ");

n=sc.nextInt();

System.out.println("Enter the weights of each items:");

for(i=0;i<n;i++)

array[0][i]=sc.nextInt();

System.out.println("Enter the values of each items:");

for(i=0;i<n;i++)

array[1][i]=sc.nextInt();

System.out.println("Enter maximum volume of knapsack :");

max_qty=sc.nextInt();

m=max_qty;

while(m>=0)

{

max=0;

for(i=0;i<n;i++)

{

if(((float)array[1][i])/((float)array[0][i])>max)

{

max=((float)array[1][i])/((float)array[0][i]);

j=i;

}

}

if(array[0][j]>m)

{

System.out.println("Quantity of item number: "+ (j+1) + " added is " +m);

sum+=m*max;

m=-1;

}

else

{

System.out.println("Quantity of item number: " + (j+1) + " added is " + array[0][j]);

m-=array[0][j];

sum+=(float)array[1][j];

array[1][j]=0;

}

}

System.out.println("The total profit is " + sum);

sc.close();

}

}

Output

Output


For more VTU IV Sem DAA Lab Experiments Click here


Our Mentors(For AI-ML)


Sharda Godara Chaudhary

Mrs. Sharda Godara Chaudhary

An alumna of MNIT-Jaipur and ACCENTURE, Pune

NISHA (IIT BHU)

Ms. Nisha

An alumna of IIT-BHU

Related questions

 Goeduhub:

About Us | Contact Us || Terms & Conditions | Privacy Policy || Youtube Channel || Telegram Channel © goeduhub.com Social::   |  | 
...