Greedy
A greedy algorithm builds an answer by taking the locally best choice at each step. It is correct only when that local rule is proven to lead to a global optimum — or when you accept an approximation.
Detailed Explanation
Interval scheduling is the usual teaching example: pick the meeting that ends first, repeat on the remainder. Sorting by end time plus one scan is O(n log n) and optimal. A greedy that picked the shortest meeting instead can be wrong. The algorithm is the rule plus the proof (or a well-known theorem), not "it looked good on one example."
Go shape. Sort with slices.SortFunc, then a single range. Keep a running end time, a running sum, or a heap of current best options (hybrid greedy). The sort key is the greedy choice. If you cannot name the key in one phrase, you may not have a greedy algorithm yet.
When greedy fails. Knapsack with indivisible items: taking the highest value/weight first can lose to a different subset. Those problems need DP or search. Coin change is greedy only for certain coin systems (US coins, yes; arbitrary denominations, no).
Exchange arguments. The usual proof: any optimal solution can be transformed into the greedy one without losing quality, by swapping a differing choice. If you cannot sketch that, treat the greedy as a heuristic and test it, or use DP.
What it costs. Typically one sort and a linear scan: O(n log n) time, O(1) extra if you sort in place. A greedy that uses a heap (Huffman, merging files) is O(n log n) with container/heap. Prefer greedy when it is proven and the code stays shorter than the DP table.
Code Examples
package main
import (
"cmp"
"fmt"
"slices"
)
type interval struct{ start, end int }
func maxMeetings(in []interval) int {
slices.SortFunc(in, func(a, b interval) int {
return cmp.Compare(a.end, b.end)
})
count, end := 0, -1
for _, m := range in {
if m.start >= end {
count++
end = m.end
}
}
return count
}
func main() {
fmt.Println(maxMeetings([]interval{{1, 3}, {2, 5}, {4, 7}})) // 2
}func minCoinsUS(cents int) int {
coins := []int{25, 10, 5, 1}
n := 0
for _, c := range coins {
n += cents / c
cents %= c
}
return n
}Common Gotchas
A greedy rule that works on samples can be wrong in general
prove it or fall back to DP.
Sorting the wrong key is a different algorithm
"shortest first" is not "ends first."
In-place `SortFunc` mutates the caller's slice
copy if the original order is needed.
Coin change is not always greedy
test arbitrary denominations with DP.