Skip to content
  • Dashboard
  • Review
  • Go: plan & chat
  • Roadmap
  • Patterns & lessons49
  • Sheets
  • Problems1.5k
  • Ascend
  • Toolkit
  • Core CS + SQL
  • System Design
  • Machine Coding
  • Interview hub
  • Mock interview
  • Companies & OA
  • Leaderboard
  • Battles
  • College Cup
  • People

Keep your progress

Sync across devices with a free account.

Sign upSign in
Patterns & lessons
Sign inSign up
Patterns/Greedy/Greedy

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
Practise nextIncreasing Array II
IdeaPracticePitfalls

Recognise it

The signal

process in time order and keep the best set under a budget

  1. 1Brute force

    DP over (index, budget) or trying all subsets.

  2. 2The observation

    Deciding irrevocably too early: the heap lets you revise the cheapest past decision in O(log n).

  3. 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

Next

Increasing Array II

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

Resources

  • Greedy Algorithms with SortingUSACO Guide · course
  • Greedy Algorithms (chapter)Jeff Erickson · book
  • Exchange arguments (sorting with dp)Errichto · blog
  • Algorithms playlistAbdul Bari · video
  • Competitive Programmer's HandbookAntti Laaksonen · book
TodayReviewPatternsProblems