Greedy algorithm
Жадный алгоритм
A greedy algorithm builds a solution one step at a time, taking the option that looks best under a fixed rule and never undoing that choice. Whether this produces the best overall result depends on the problem and the rule.
What makes an algorithm greedy?
A greedy algorithm commits to a choice based on what looks best at the current step. It does not compare all the solutions that might follow from each choice. The hard part is usually not writing the loop but finding a rule you can prove will lead to an optimal answer.
Example: scheduling one meeting room
Suppose you have a list of meetings with fixed start and end times, and your goal is to fit in as many as possible without overlap. Each meeting has positive duration, and meetings are allowed to touch at their endpoints. Picking the earliest start is tempting, but a meeting from 9:00 to 12:00 would block three one-hour meetings that could fit in the same window. Instead, pick the meeting that finishes first, then repeat among meetings that start no earlier than its finish time.
def schedule(meetings):
chosen = []
for start, end in sorted(meetings, key=lambda meeting: meeting[1]):
if not chosen or start >= chosen[-1][1]:
chosen.append((start, end))
return chosen
For n meetings, sorting takes O(n log n) time and the scan takes O(n). If the input already comes in finish-time order, the scan alone is enough.
Why this choice is safe
Start with any schedule that fits the maximum number of meetings. If its first meeting isn't the one that finishes earliest, swap in the earliest finisher. The replacement ends no later than the original first meeting, so none of the later meetings need to move. The schedule still fits the same number of meetings. This is an exchange argument: it shows that at least one optimal solution begins with the greedy choice. After making that choice, you're solving the same scheduling problem on the remaining compatible meetings, so the reasoning applies again.
Where it works and where it fails
Greedy choices drive Kruskal's minimum spanning tree algorithm and Dijkstra's shortest-path algorithm for graphs with nonnegative edge weights. But even a small change to a problem can make a proven rule stop working. If meetings have different payouts and the goal is maximum total payout, taking the earliest finisher might block a much more valuable meeting. Dynamic programming can handle that version by comparing the best outcomes from taking or skipping a meeting.
What interviewers look for
State the objective and the choice rule separately. Then either justify the rule or try to break it with a tiny input. If you use an exchange argument, say exactly what you're replacing and why the replacement preserves both feasibility and the objective value in your example. Finally, account for preprocessing: a linear scan after a sort does not make the whole algorithm linear.