DSA · Intermediate · Pattern 7 of 10
Greedy
17 problems.
Your progress0%
- 1st Visit
- 0/17
- 2nd Visit
- 0/17
- Revise
- 0/17
About this pattern
A greedy algorithm makes the locally best choice at each step and never revisits it. It is correct only when an exchange argument holds: any optimal solution can be transformed, without becoming worse, into one that agrees with the greedy choice. Most greedy solutions start by sorting on a well-chosen key, then scan once while maintaining a running state such as the farthest reachable index, the remaining fuel or the last occupied position.
Signals include maximising a count or minimising a cost where choices interact only through simple state. Before coding, try to break your rule with a small counterexample. Typical cost is O(n log n) for sorting plus an O(n) scan.
// Sort by the key that makes the local choice safe, then scan once.
sort(items.begin(), items.end(), [](const Item& x, const Item& y) {
return x.key < y.key;
});
long long state = initialState, answer = 0;
for (const Item& it : items) {
if (canTake(state, it)) { // the greedy decision
state = update(state, it);
++answer;
}
}