1/0 knapsack solve using greedy method
The knapsack problem is an example of a computational optimization problem, a topic in mathematics and computer science about finding the optimal object among a set of objects.
When weights and values of n items are given, these items are to be put in a knapsack of total capacity of W to get maximum value in the knapsack. In other words, two integer arrays with given value of [0….n-1] and of weight [0….n-1] which represents values and weights associated with n items respectively and given integer W represents knapsack capacity. Find out the subset with maximum value [] such that sum of the weights of this subset is smaller than or equal to W.
Two types of Knapsack
1. Binary Knapsack (0/1)
You cannot break an item, either pick the complete item, or leave entire item (0–1 property or called Binary Knapsack).Greedy approach not gives always Optimal Solution in Binary Knapsack.
2. Fractional Knapsack
we can break items for maximizing the total value of knapsack. This problem in which we can break an item is also called the fractional knapsack problem.Greedy approach gives always Optimal Solution in Fractional Knapsack
Example:-
Knapsack Max weight : W = 15 (units)
Total items : N = 3
Values of items : value [] = {60, 80,70}
Weight of items : weight [] = {7, 8, 6}
Here we have W (called limit) is 15 and a set of items, each with a weight and a value Determine the number of each item to include in collection so that the total weight of collection is less than or equal to W and value of collection is as large as possible.
Since this is the 0–1 knapsack problem, we can either include an item in our knapsack or exclude it, but cannot include a fraction of it.
Solution:-
We have multiple solutions but we have to find an optimal solution
Weight =7+8 (15), value = 60+80 (140)
Weight =7+6 (13), value = 60+70 (130)
Weight =8+6 (14), value = 80+70 (150)
Weight =7+8+6 (21) > 15,
So here we find optimal solution is
weight = 8+6 (14) is less than W and value = 80+70 (150) so our condition also satisfies so we get maximum value from the given sets of items
Time Complexity: O(nW) where n is the number of items and W is the capacity of knapsack.
Clik here to view.

In this example we can pick up laptop and necklace so our total capacity is 6 and total value is 6000
References:Image may be NSFW.
Clik here to view.
