Greedy Approach
Greedy Approach
Greedy Algorithm
To begin with, the solution set (containing answers) is empty.
1. At each step, an item is added to the solution set until a solution is
reached.
2. If the solution set is feasible, the current item is kept.
3. Else, the item is rejected and never considered again.
Problem: You have to make a change of an amount using the smallest possible number of
coins.
Amount: $18
Available coins are
$5 coin
$2 coin
$1 coin
Solution:
1. Create an empty solution-set = { }. Available coins are {5, 2, 1}.
2. We are supposed to find the sum = 18. Let's start with sum = 0.
3. Always select the coin with the largest value (i.e. 5) until the sum > 18. (When we
select the largest value at each step, we hope to reach the destination faster. This
concept is called greedy choice property.)
4. In the first iteration, solution-set = {5} and sum = 5.
5. In the second iteration, solution-set = {5, 5} and sum = 10.
6. In the third iteration, solution-set = {5, 5, 5} and sum = 15.
7. In the fourth iteration, solution-set = {5, 5, 5, 2} and sum = 17. (We cannot select 5
here because if we do so, sum = 20 which is greater than 18. So, we select the 2nd
largest item which is 2.)
8. Similarly, in the fifth iteration, select 1. Now sum = 18 and solution-set = {5, 5, 5, 2,
1}.
In this method, the Knapsack's filling is done so that the maximum capacity of
the knapsack is utilized so that maximum profit can be earned from it. The
knapsack problem using the Greedy Method is referred to as:
Given a list of n objects, say {I1, I2,……, In) and a knapsack (or bag).
The capacity of the knapsack is M.
Each object Ij has a weight wj and a profit of pj
If a fraction xj (where x ∈ {0...., 1)) of an object Ij is placed into a knapsack,
then a profit of pjxj is earned.
The problem (or Objective) is to fill the knapsack (up to its maximum capacity
M), maximizing the total profit earned.
Problem-
For the given set of items and knapsack capacity = 60 kg, find the optimal solution
for the fractional knapsack problem making use of greedy approach.
OR
Find the optimal solution for the fractional knapsack problem making use of greedy
approach. Consider-
n=5
w = 60 kg
(w1, w2, w3, w4, w5) = (5, 10, 15, 22, 25)
(b1, b2, b3, b4, b5) = (30, 40, 45, 77, 90)
Solution-
Step-01:
Compute the value / weight ratio for each item-
Step-02:
Sort all the items in decreasing order of their value / weight ratio-
I1 I2 I5 I4 I3
(6) (4) (3.6) (3.5) (3)
Step-03:
Start filling the knapsack by putting the items into it one by one.
Now,
Knapsack weight left to be filled is 20 kg but item-4 has a weight of 22 kg.
Since in fractional knapsack problem, even the fraction of any item can be
taken.
So, knapsack will contain the following items-
< I1 , I2 , I5 , (20/22) I4 >