Two City Scheduling

MediumGreedyLeetCode 1029 ↗World 7-16
0:00 / 0:00

Send 2n people to two cities at least cost: book everyone to B, sort by A minus B, and switch the cheapest half to A.

▼

The problem

LeetCode 1029 (Medium). 2n people must travel. costs[i] = [aCost, bCost] is what person i costs to fly to city A or to city B. Send exactly n people to each city at the minimum total cost.

Examples (LeetCode's): - [[10,20],[30,200],[400,50],[30,20]] gives 110: the first two go to A and the last two to B.

TRY IT ON LEETCODE ▶

The solution

def two_city_sched_cost(costs):
    costs.sort(key=lambda c: c[0] - c[1])
    n = len(costs) // 2
    total = 0
    for i, (a, b) in enumerate(costs):
        total += a if i < n else b
    return total

Transcript

Two City Scheduling. Two n people must fly out. Each has two prices: one to city A and one to city B. Send exactly n to each city, at the smallest total cost.

Take four travelers: ten or twenty, thirty or two hundred, four hundred or fifty, and thirty or twenty. Two go to each city, and the best split costs one hundred ten.

The direct way tries every choice of n people for city A. Four travelers give six splits, but twenty give one hundred eighty-four thousand, seven hundred fifty-six.

A tempting shortcut: send everyone to their cheaper city. With these six travelers, that's one for A and five for B, but each coach seats three. Someone has to switch. But who?

Here's the key idea. First, book everyone to city B: for our four, that's two hundred ninety. Moving one person to A changes the total by their A price minus their B price, and a negative change is a saving. So sort by A minus B, and move the first n to city A.

In code, sort the costs by A minus B. The first half pays their A price, the rest pay B, and we add it up.

Back to the four. The differences are minus ten, minus one seventy, three fifty and ten. Sorted, minus one seventy and minus ten come first, so they go to A: two ninety minus one eighty is one hundred ten.

Now the six. All on B costs twenty-two seventeen. Minus five eleven saves the most, so that traveler moves first. A still needs two more, so it takes the smallest extras, forty-five and one hundred eight. The total: eighteen fifty-nine.

Sorting takes n log n time, and the sum is one pass, with constant extra space beside the sort.

Book everyone to B, sort by A minus B, and send the first half to A. That's Two City Scheduling.