SDE & MLE Prep

1029. Two City Scheduling

Problem

A company will interview 2n people; costs[i] = [aCost, bCost] is the cost of flying person i to city A or city B. Send exactly n people to each city at minimum total cost.

Example: [[10,20],[30,200],[400,50],[30,20]] → 110

Send everyone to A, then switch the n people with the most negative costB − costA to B. Equivalently, sort by costA − costB: first half → A, second half → B.

Complexity: O(n log n).

class Solution:
    def twoCitySchedCost(self, costs: List[List[int]]) -> int:
        costs.sort(key=lambda c: c[0] - c[1])
        n = len(costs) // 2
        return sum(a for a, _ in costs[:n]) + sum(b for _, b in costs[n:])