Technique
Greedy with a Heap (regret / exchange later)
Take items greedily, keep taken items in a heap, and when a constraint breaks, undo the worst earlier choice (or swap it for a better one).
Learn firstGreedyTop-K Elements
0%
mastery
0/7 solved
0/7 solved
Recognise it
The signal
process in time order and keep the best set under a budget
1Brute force
DP over (index, budget) or trying all subsets.
2The observation
Deciding irrevocably too early: the heap lets you revise the cheapest past decision in O(log n).
3Why it works
The kept set is the best possible for the prefix processed so far under the constraint.
Reach for it when
- +ladders/bricks, potions
- +deadlines with profits
Not when
- ×the choice to undo is not simply the min/max of the kept set
Practice
0/7 solved
- Increasing Array IICSESMedium
- Furthest Building You Can ReachGoogle, UberMedium
- Potions (Hard Version)Codeforces1600
- Potions (Easy Version)Codeforces1500
- Sonya and Problem Wihtout a LegendCodeforces2300
- SequenceCodeforces2200
- Buy Low Sell HighCodeforces2400
Pitfalls
Misconceptions
- !equating it with plain top-k (here items are evicted only when a constraint is violated)
Go deeper1 combinations · resources
Combinations
Greedy with a Heap (regret / exchange later)+Top-K Elements
survive constraints over time (health, bricks), maximise count taken
- Greedy with a Heap (regret / exchange later):
- take greedily, undo the worst past choice when a constraint breaks
- Top-K Elements:
- min-heap of taken items
Furthest Building You Can ReachPotions (Hard Version)Buy Low Sell High