Two City Scheduling
Difficulty: Medium · Pattern: Greedy · LeetCode #1029
2n people are interviewing. costs[i] = [aCost, bCost] is the cost of flying person i to city A or to city B. Exactly n people must go to each city. Return the minimum total cost.
Examples
text
[[10,20],[30,200],[400,50],[30,20]] → 110 (A: 10, 30; B: 50, 20)
[[259,770],[448,54],[926,667],[184,139],[840,118],[577,469]] → 1859Hints
- Pretend everyone flies to B first. Moving person i to A then changes the cost by
a − b. - Pick the n people for whom that change is smallest (most negative).
Approach
Sort the people by a − b ascending. The first n go to A and the rest to B.
Why it works: total = Σb + Σ over the A-group of (a − b). Σb is fixed, so the problem is choosing the n smallest values of (a − b). Sorting by that difference is exactly right. It's a clean example of a greedy proven by rewriting the objective.
Complexity
Time: O(n log n). Space: O(n).
Python solution
def twoCitySchedCost(costs):
costs = sorted(costs, key=lambda c: c[0] - c[1])
n = len(costs) // 2
return sum(c[0] for c in costs[:n]) + sum(c[1] for c in costs[n:])JavaScript solution
function twoCitySchedCost(costs) {
const c = [...costs].sort((x, y) => (x[0] - x[1]) - (y[0] - y[1])), n = c.length / 2;
let total = 0;
c.forEach(([a, b], i) => { total += i < n ? a : b; });
return total;
}