DAA Greedy Method,Knacksackprob
DAA Greedy Method,Knacksackprob
Chapter-3
Greedy Method
Greedy algorithms build a solution part by part, choosing the next part in such a way, that it
gives an immediate benefit. This approach never reconsiders the choices taken previously. This
approach is mainly used to solve optimization problems.
In many problems, it does not produce an optimal solution though it gives an approximate
(near optimal) solution in a reasonable time.
1. Way of greedy selection: Select which solution is best at present and then solve the
subproblem arising from making the last selection. The selection of greedy algorithms
may depend on previous selections. But it cannot depend on any future selection or
depending on the solutions of subproblems.
The algorithm evolves in a way that makes selections in a loop, at the same time
shrinking the given problem to smaller subproblems.
2. Optimal substructure: You perform the optimal substructure for a problem if the
optimal solution of this problem contains optimal solutions to its subproblems.
Areas of Application
Fractional Knapsack
The Greedy algorithm could be understood very well with a well-known problem referred to as
Knapsack problem.
Although the same problem could be solved by employing other algorithmic
approaches(Dynamic programming), Greedy approach solves Fractional Knapsack problem
reasonably in a good time.
Knapsack Problem
Applications
Problem Scenario
A thief is robbing a store and can carry a maximal weight of W into his knapsack. There are n
items available in the store and weight of ith item is wi and its profit is pi. What items should
the thief take?
The items should be selected in such a way that the thief will carry those items for which he
will gain maximum profit. Hence, the objective of the thief is to maximize the profit.
Based on the nature of the items, Knapsack problems are categorized as
Fractional Knapsack
The ith item contributes the weight xi, wi to the total weight in the knapsack and profit xi,pi to
the total profit.
Hence, the objective of this algorithm is to
It is clear that an optimal solution must fill the knapsack exactly; otherwise we could add a
fraction of one of the remaining items and increase the overall profit.
Page-4
Analysis
If the provided items are already sorted into a decreasing order of pi/wi then the
whileloop takes a time in O(n); Therefore, the total time including the sort is
in O(n logn).
Page-5
Now, the capacity of the Knapsack is equal to the selected items. Hence, no more items can be
selected.
And the total profit is 100 + 280 + 120 * (10/20) = 380 + 60 = 440
This is the optimal solution. We cannot gain more profit selecting any different combination of
items.