The greedy strategy works as follows:
To find an optimal solution, we construct the solution
by making decisions to choose each item to add to
the solution optimally, and never reversing decisions
already made.
A greedy algorithm for the problem runs like this:
use as many 25¢ as possible, then
use as many 10¢ as possible, then
use as many 5¢ as possible, then finally
use as many 1¢ as possible.
For example, to make change for 30¢, the greedy algorithm uses 6 coins (25 + 1 + 1 + 1 + 1 + 1). However, we can use 3 coins (10 + 10 + 10) instead.
High-level algorithm
1. Sort the classes into nondecreasing order using their finish times as key.
Now we have classes j = 1, ⋯ , n with start times S[j], and finish times F[j],
with F[1] ≤ F[2] ≤ ⋯ ≤ F[n-1] ≤ F[n].
2. Find the optimum schedule as follows.
Sc ← ∅
/*
* We maintain variable f equal to the finish time
* of the last class scheduled.
*/
f ← -∞
for j ← 1 to n do {
if S[j] ≥ f then {
Sc ← Sc ∪ {j}
f ← F[j]
}
}
return Sc as the desired schedule