Greedy
A greedy algorithm builds a solution by taking the locally best choice at each step and never retracting it. It is fast when a proof says those choices compose into a global optimum. Without a proof it is a heuristic.
Detailed Explanation
You are scheduling talks into one room. At each step you pick the remaining talk that finishes first. That is greedy: a local rule (earliest finish), no backtracking. It happens to be optimal. Picking the shortest talk, or the talk that starts first, is also greedy and is not optimal. The difference is a proof, not the style of the loop.
Greedy works when the problem has greedy choice (an optimal solution exists that includes the local pick) and optimal substructure (the rest is the same problem on a smaller instance). Interval scheduling, Huffman codes, Dijkstra (with non-negative weights), Kruskal and Prim, and "minimum number of coins" for canonical coin systems are the textbook yeses. Knapsack with integer weights, coin change with arbitrary denominations, and longest path are the textbook nos — those need DP or search.
The C++ shape is often: sort, then a single scan. Sort intervals by end time, then take an interval if it starts after the last accepted end. Sort jobs by deadline. Put values in a priority_queue and repeatedly take the top (Huffman, "connect ropes").
Because you do not revisit a choice, time is usually O(n log n) from the sort or the heap, and space is O(1) extra plus the output. That is the appeal versus DP's tables.
When an interviewer says "can you do better than DP?", they mean "is there a greedy?". Your job is to try a counter-example. Two intervals where the greedy pick blocks a better pair. If you cannot find one after serious effort, sketch the exchange argument: take any optimal solution that differs from greedy at the first choice, swap in the greedy choice, show the solution does not get worse.
Greedy as a heuristic (set cover, many NP-hard problems) is fine in production if you measure approximation quality. Do not call it optimal in a comment.
std::priority_queue and std::set are the usual supporting structures. Sorting plus a scan is the first thing to try.
Code Examples
#include <algorithm>
#include <iostream>
#include <utility>
#include <vector>
int maxTalks(std::vector<std::pair<int, int>> talks) { // {start, end}
std::sort(talks.begin(), talks.end(),
[](auto a, auto b) { return a.second < b.second; });
int taken = 0;
int end = -1;
for (auto [s, e] : talks) {
if (s >= end) {
++taken;
end = e;
}
}
return taken;
}
int main() {
std::vector<std::pair<int, int>> talks{{1, 3}, {2, 5}, {4, 6}};
std::cout << maxTalks(talks) << '\n'; // prints: 2
}#include <queue>
#include <vector>
int minCostConnect(std::vector<int> lengths) {
std::priority_queue<int, std::vector<int>, std::greater<int>> q(
lengths.begin(), lengths.end());
int cost = 0;
while (q.size() > 1) {
int a = q.top(); q.pop();
int b = q.top(); q.pop();
cost += a + b;
q.push(a + b);
}
return cost;
}
int main() {
return minCostConnect({1, 2, 3}) == 9 ? 0 : 1; // (1+2)+3 = 3+6, cost 3+6=9
}Common Gotchas
Treating a heuristic as a proof
coin change with denominations `{1, 3, 4}` and amount 6 is greedy-4+1+1=3 coins, optimal is 3+3. Test a counter-example.
Dijkstra is greedy and needs non-negative weights
a negative edge breaks the "first time I pop is final" argument.
The sort is the algorithm
if you sort by the wrong key, you have a different (often wrong) greedy.
Floating-point scores
greedy on `double` profit ratios can mis-order near ties. Use exact fractions or integers when the proof needs exact order.