Greedy
A greedy algorithm builds a solution by taking the locally best choice at each step and never retracting it. It is fast when the problem has the greedy-choice property, and wrong when it does not.
Detailed Explanation
At each step you pick the option that looks best now: the smallest remaining number, the earliest finishing interval, the highest value-per-weight item. You do not explore alternatives. There is no table of subproblems and no backtracking. Time is usually the cost of sorting plus a linear pass.
The greedy-choice property says that some globally optimal solution contains the choice you just made. The optimal-substructure property says the rest of the instance can be solved the same way. Interval scheduling (most non-overlapping meetings: always take the one that finishes first) has both. 0-1 knapsack does not: taking the highest value-per-weight item can block a better combination. Fractional knapsack does: you may take part of an item.
C implementations are sorts plus scans. qsort the array of intervals by finish time, then walk once, accepting an interval when its start is at least the last finish. That is O(n log n) and a few integers of extra state. If you cannot sort — streaming data, online constraints — the greedy choice has to be maintainable in a heap or a running extremum.
Proving greedy is the job. A swap argument (any optimal solution can be rewritten to include your first choice without getting worse) is the usual pattern. If you cannot sketch that argument, write a counterexample search for small n before you ship. Interviewers will ask for the counterexample to the wrong greedy (longest interval first, and so on).
Greedy is not DP with a smaller table. DP considers multiple options per state. Greedy considers one. Huffman coding, Dijkstra's algorithm, Kruskal's MST, and coin systems with a canonical denomination set are greedy. Making change in the US is greedy; making change in a system with coins {1, 3, 4} for amount 6 is not (4+1+1 loses to 3+3).
Code Examples
#include <stdio.h>
#include <stdlib.h>
struct Iv { int start, finish; };
static int by_finish(const void *a, const void *b)
{
const struct Iv *x = a, *y = b;
if (x->finish < y->finish) return -1;
if (x->finish > y->finish) return 1;
return 0;
}
static int schedule(struct Iv *v, int n)
{
qsort(v, (size_t)n, sizeof v[0], by_finish);
int taken = 0;
int last = -1;
for (int i = 0; i < n; i++) {
if (v[i].start >= last) {
taken++;
last = v[i].finish;
}
}
return taken;
}
int main(void)
{
struct Iv v[] = { {0, 3}, {1, 2}, {2, 5}, {4, 6} };
printf("%d\n", schedule(v, 4)); /* prints: 2 (1-2 and 4-6) */
return 0;
}#include <stdio.h>
/* Canonical coin system: greedy works for 1,5,10,25. */
static int coins(int amount)
{
int den[] = { 25, 10, 5, 1 };
int n = 0;
for (int i = 0; i < 4; i++) {
n += amount / den[i];
amount %= den[i];
}
return n;
}
int main(void)
{
printf("%d\n", coins(40)); /* prints: 3 (25+10+5) */
return 0;
}Common Gotchas
A greedy that works on one instance is not a proof
try a designed counterexample, especially for knapsack-shaped problems.
Sorting is usually the real cost
if the compare is wrong, the greedy walk is faithfully wrong.
Dijkstra is greedy and needs non-negative weights
a negative edge breaks the "first time I reach you is best" claim.
Mutating the input during `qsort` while also holding pointers into it invalidate
Mutating the input during `qsort` while also holding pointers into it invalidates those pointers