Loading
Loading
Take the locally best option, when you can prove it stays best.
Make the choice that looks best right now and never reconsider it. This is only correct when the problem has an exchange property: any optimal solution can be transformed into one containing your greedy choice without getting worse. Without that argument, a greedy algorithm is a guess that passes the samples.
The algorithm is usually two lines. The work is the proof: show that swapping the greedy choice into any optimal solution keeps it optimal. Without that, you have a heuristic.
The shape, not a solution. Adapt the condition and the state to the problem in front of you.
def max_non_overlapping(intervals): """ Select the most intervals that do not overlap. Sort by END time, not start. Exchange argument: the interval that ends soonest leaves the most room for everything after it, so some optimal solution contains it. """ intervals.sort(key=lambda pair: pair[1]) count = 0 last_end = float("-inf") for start, end in intervals: if start >= last_end: count += 1 last_end = end return count def min_removals_to_fit(items, capacity): """Sort so the cheapest concession comes first, then take while it fits.""" items.sort() used = 0 taken = 0 for item in items: if used + item > capacity: break used += item taken += 1 return taken| Status | Problem | Difficulty | Role |
|---|---|---|---|
| Best Single Trade#7 | Easy | Primary | |
| Fewest Hops to the Exit#55 | Easy | Related | |
| Stepping Stones Across the Stream#71 | Easy | Primary | |
| Portions for Appetites#72 | Easy | Primary | |
| Exact Change at the Ferry Booth#73 | Easy | Primary | |
| Loading the Supply Truck#74 | Easy | Primary | |
| Balanced Dance Phrases#76 | Easy | Primary | |
| Forced Sign Flips#77 | Easy | Primary | |
| Fewest Darts for the Banners#81 | Medium | Primary | |
| Trim the Talk Schedule#82 | Medium | Primary | |
| Where the Shuttle Should Start#84 | Medium | Primary | |
| Split the Parade#85 | Medium | Primary | |
| Ferrying Hikers Across the Lake#86 | Medium | Primary | |
| Biggest Badge Number#87 | Medium | Primary | |
| Reward Tokens for the Relay Team#88 | Hard | Primary | |
| Fewest Sprinklers for the Lawn#89 | Hard | Primary | |
| Fewest Depot Stops#90 | Hard | Related | |
| Cable Splicing Cost#117 | Medium | Related | |
| Oven Cooldown Schedule#118 | Medium | Related | |
| Sensor Spacing#140 | Medium | Related | |
| Fairest Shift Split#141 | Hard | Related |
Sign in to keep a note here. It is free, and nobody else can see it.
Sign in