The knapsack problem or rucksack problem is a problem in combinatorial optimization: Given a set of items, each with a weight and a value, determine the count of each item to include in a collection so that the total weight is less than or equal to a given limit and the total value is as large as possible. It derives its name from the problem faced by someone who is constrained by a fixed-size knapsack and must fill it with the most useful items.
GreedyKnapsack (m, n)//p and w are arrays contain the profits and weights respectively of// n objects ordered such that p[i]/w[i] >= p[i+1]/w[i+1]// that is in non-increasing order.// m is the knapsack size and x is the solution vectorfor i < 1 to n dox[i]ß 0endFortotal ß mfor i ! 1 to n doif (w[i] <= total)x[i]ß1totalßtotal-w[i]else break // to exit the for-loopEndifendFor
if (i<=n) x[i] ß total/w[i]
endGreedyKnapsack
Java Program to Solve Knapsack Problem
When you run the program, the output will be:
Optimal soluation to knapsack instance with values given as follows : m=35item | profit | weight | Unit Price | Take weight0 138.0 24.0 5.75 1.01 114.0 24.0 4.75 0.45833333333333332 56.0 17.0 3.2941176470588234 0.03 101.0 51.0 1.9803921568627452 0.04 125.0 64.0 1.953125 0.05 95.0 49.0 1.9387755102040816 0.06 124.0 86.0 1.441860465116279 0.07 55.0 41.0 1.3414634146341464 0.08 93.0 89.0 1.0449438202247192 0.09 52.0 103.0 0.5048543689320388 0.0