Greedy Paradigm
Greedy Paradigm
Topics
1. Introduction
2. Does Greedy Always Work?
3. Problems & Solutions
4. Important References
Introduction
Algorithms for optimization problems typically go through a sequence of steps, with a set of
choices at each step. For many optimization problems, using dynamic programming to
determine the best choice(s) is an overkill; there are simpler and more efficient algorithms.
A greedy algorithm always makes the choice that looks best at the moment. That is, it makes
a locally optimal choice in the hope that this choice will lead to a globally optimal solution.
Greedy algorithms do not always yield optimal solutions, but for many problems they do.
Greedy is a strategy that works well on optimization problems with the following
characteristics:
Example-1
Weight 10 20 30
● Maximum profit for fractional knapsack is $240 [10 units of Item-1, 20 units of
0 units of Item-3]
Item-2, 2
● Maximum profit for integer knapsack is $
220 [I
tem-3 and I tem-2]
Solution
1. Greedy Approach: Pick elements in non-increasing order of value/unit and fill
the knapsack.
For above example we can verify that for both the knapsack problems, we get the
optimal solution using Greedy Approach. So far, greedy seems to work for both.
Example-2
Value 80 90 60 35
Weight 10 15 12 7
For integer knapsack, using greedy approach gives a maximum profit of $170 [Item-1 and
175 [Item-1, I
Item-2]. But the optimal solution for this example is $ tem-3 and I
tem-4]
Conclusion: Greedy doesn’t always work. Greedy works for fractional knapsack, but fails for
integer knapsack. Integer knapsack is solved using dynamic programming, which is discussed
in the next section.
Problems & Solutions
1. Activity-selection problem
You are given N activities with start and finish times. Select the max number of
activities that can be performed by a single person, assuming that a person can only
work on a single activity at a time.
Example: Consider the following 6 activities:
start[] = {1, 3, 0, 5, 8, 5};
finish[] = {2, 4, 6, 7, 9, 9};
The maximum set of activities that can be executed by a single person is 4, i.e.,
Activity-0, Activity-1, Activity-3, Activity-4.
Solution: Sort the activities based on finish time and pick activities in order such that
they do not overlap. Refer Proof of Optimality @Wiki for proof on why greedy
choice based on finish time works here.
2. Fractional Knapsack
4. Huffman Coding
Important References
1. Greedy is good @TopCoder
2. Greedy Algorithms @USTC
3. Greedy Tutorial @HackerEarth