Basics of Greedy Algorithms
Basics of Greedy Algorithms
Introduction
In an algorithm design there is no one 'silver bullet' that is a cure for all computation problems.
Different problems require the use of different kinds of techniques. A good programmer uses all
these techniques based on the type of problem. Some commonly-used techniques are:
A greedy algorithm, as the name suggests, always makes the choice that seems to be the
best at that moment. This means that it makes a locally-optimal choice in the hope that this
choice will lead to a globally-optimal solution.
Assume that you have an objective function that needs to be optimized (either maximized or
minimized) at a given point. A Greedy algorithm makes greedy choices at each step to ensure
that the objective function is optimized. The Greedy algorithm has only one shot to compute the
optimal solution so that it never goes back and reverses the decision.
Being a very busy person, you have exactly T time to do some interesting things and you want
to do maximum such things.
You are given an array A of integers, where each element indicates the time a thing takes for
completion. You want to calculate the maximum number of things that you can do in the limited
time that you have.
This is a simple Greedy-algorithm problem. In each iteration, you have to greedily select the
things which will take the minimum amount of time to complete while maintaining two
variables currentTime and numberOfThings. To complete the calculation, you must:
currentTime = 1
numberOfThings = 1
currentTime is 1 + 2 = 3
numberOfThings = 2
currentTime is 3 + 3 = 6
numberOfThings = 3
After the 4th iteration, currentTime is 6 + 4 = 10, which is greater than T. Therefore, the answer
is 3.
Implementation
#include <iostream>
#include <algorithm>
int main()
{
int T, N, numberOfThings = 0, currentTime = 0;
cin >> N >> T;
for(int i = 0;i < N;++i)
cin >> A[i];
sort(A, A + N);
for(int i = 0;i < N;++i)
{
currentTime += A[i];
if(currentTime > T)
break;
numberOfThings++;
}
cout << numberOfThings << endl;
return 0;
}
This example is very trivial and as soon as you read the problem, it is apparent that you can
apply the Greedy algorithm to it.
Examples
The greedy method is quite powerful and works well for a wide range of problems. Many
algorithms can be viewed as applications of the Greedy algorithms, such as (includes but is not
limited to):