DSA Factory
Free Greedy lessonsGreedy · Stage 1 · Sort then choose · Step 3

Send people to two cities

Fly half the people to each of two cities at the lowest total cost, by sorting people on how much cheaper city A is than city B. About 15 minutes.

Compare by the difference

A company flies 2n people to interview: exactly n go to city A and n go to city B. Each person has a cost for each city. You want the lowest total.

Looking at one cost alone misleads. What matters is how much you gain by sending a person to A rather than B. Start by pretending everyone goes to B, then ask who saves the most by switching to A.

Saving of A over B: is the cost of A minus the cost of B.
Not the cheapest alone, compare the two cities together.

Sort and split

Sort people by cost of A minus cost of B, smallest first. The people at the front gain the most from going to A, or lose the least.

Send the first n of them to A and the remaining n to B. Add up the matching costs. Swapping any pair across the split could only make the sum larger, which is why the greedy order is safe.

First half: goes to city A.
Second half: goes to city B.
In code
people.sort(key=lambda p: p[0] - p[1])
half = len(people) // 2
total = 0
for i, (a, b) in enumerate(people):
    total += a if i < half else b
Costs [A, B] per person, sorted by the difference A − B.
ABA−Bcity
P1
10
20
-10
P2
30
200
-170
A
P3
400
50
350
P4
30
20
10
total
30

P2 saves 170 by going to A. Send to A.

Move 1 of 4
Quick check

Costs [A, B]: [10, 20], [30, 200], [400, 50], [30, 20]. Who is sent to A first?

  1. AThe person with costs [30, 200]
  2. BThe person with costs [10, 20]
  3. CThe person with costs [400, 50]
Show the answer

The person with costs [30, 200]. A costs 170 less than B for them, the biggest saving.

Your problem

Send to two cities

You must send 2n people to two cities, exactly n to each. You are given costs, where costs[i] = [a, b] is the cost of sending person i to city A and city B. Return the lowest total cost.

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

0 ≤ costs.length ≤ 100,000 and even · 1 ≤ a, b ≤ 1,000

Solve it in your browserFree account, no card. Python, C++, Java or JavaScript, with hints if you get stuck, and your progress is saved.
Sign up free to solve