0

Greedy with Exchange Argument

Sort by the quantity that makes the local choice obviously safe, then prove swapping any other choice is no better.

GreedyO(n log n)New46 problems
18
mastery

Trigger phrases

If a problem statement sounds like one of these, try this pattern first.

minimum number of X
schedule to maximise count
jump game
gas station

The template

Get this into muscle memory, then adapt the condition per problem.

items.sort(byTheRightKey);
let taken = 0, cursor = -Infinity;
for (const it of items)
  if (it.start >= cursor) { taken++; cursor = it.end; }

If you are stuck

The generic hint ladder for this pattern, in order.

  1. 1Try the obvious greedy on a small case and look for a counterexample.
  2. 2The right sort key is usually the constraint you are fighting.
  3. 3If you cannot justify it, switch to DP.

Drill it

Every problem in the bank that uses this pattern.

0 / 46 solved
1
MGreedy
2
3
4
5
6
7
MHeap / Priority Queue
8
MStacks & Queues
9
10
11
12
13
MHeap / Priority Queue
14
15
16
HGreedy
17
18
19
MStacks & Queues
20
21
22
EHeap / Priority Queue
23
24
MStacks & Queues
25
26
27
28
29
30
31
32
33
MSorting
34
HHeap / Priority Queue
35
36
37
38
39
40
41
HStrings
42
43
44
45
46