Greedy Algorithms8 sections · 316 units
Open in Course

Two City - Greedy Insight

Sort by savings

For each person, compute the savings of sending them to A instead of B: cost[i][0]cost[i][1]cost[i][0] - cost[i][1]. A negative savings means A is cheaper. A positive savings means B is cheaper. Sort by this difference. Send the first nn people (most benefit from A) to city A, and the rest to city B. Why this works: you are prioritizing people who benefit most from each city. Sorting by difference measures opportunity cost, not absolute cost.

This maximizes total savings by ensuring people who benefit most from each city go to that city.