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:])
assert Solution().twoCitySchedCost([[10, 20], [30, 200], [400, 50], [30, 20]]) == 110
assert Solution().twoCitySchedCost([[259, 770], [448, 54], [926, 667], [184, 139], [840, 118], [577, 469]]) == 1859
class Solution {
public int twoCitySchedCost(int[][] costs) {
Arrays.sort(costs, (x, y) -> (x[0] - x[1]) - (y[0] - y[1]));
int n = costs.length / 2, total = 0;
for (int i = 0; i < costs.length; i++) total += i < n ? costs[i][0] : costs[i][1];
return total;
}
}
func twoCitySchedCost(costs [][]int) int {
sort.Slice(costs, func(i, j int) bool { // most to gain from city A first
return costs[i][0]-costs[i][1] < costs[j][0]-costs[j][1]
})
n, total := len(costs)/2, 0
for i, c := range costs {
if i < n {
total += c[0]
} else {
total += c[1]
}
}
return total
}