Python coding

Cheapest even split between two cities

A company flies 2n candidates to on-site interviews: exactly n of them go to city A and the other n to city B. costs[i] = [a, b] is the price of flying candidate i to A and to B. Return the lowest possible total price.

costs has an even length and may be empty; prices are non-negative integers. Aim for O(n log n).

Besides the tests, one large input (3,000 candidates) with a ~150 ms limit (scaled to your device's speed): brute force won't pass.

  • cheapest_split([[40,10],[15,60],[70,62],[20,25]]) → 107
  • cheapest_split([[5,9],[3,1]]) → 6
  • cheapest_split([[1,10],[2,20],[3,30],[4,40]]) → 37
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Picture everyone booked to B first. Moving candidate i to A changes the total by a - b, and exactly n candidates must move.

Hint 2

So move the n with the smallest a - b: sort by that difference, send the first half to A and the rest to B.

Hint 3

Sorting by the cheaper price, or by a alone, fails: a candidate cheap everywhere may be the one who saves least by choosing A.

Solution and why it works
pythonO(n log n) · O(n)
def cheapest_split(costs: list[list[int]]) -> int:
    # a - b is what a candidate saves by flying to A instead of B: the most negative go to A
    order = sorted(costs, key=lambda c: c[0] - c[1])
    half = len(order) // 2
    return sum(a for a, _ in order[:half]) + sum(b for _, b in order[half:])

Book everyone to B: moving candidate i to A adds a - b, and exactly n must move, so move the n smallest differences. As an exchange argument: if someone with a larger a - b flies to A while someone with a smaller one flies to B, swapping them changes the total by the smaller difference minus the larger, which is never positive. The traps: sorting by either price alone, and a DP over how many went to A, correct but O(n²).