Two City Scheduling

Send 2n people half to A, half to B minimizing total cost — sort by cost difference.

Medium
Time O(n log n) Space O(1)
LeetCode
3 min read
greedy sorting

Problem#

costs[i] = [costToA, costToB]. Send exactly n people to each city to minimize total cost.

Examples#

  • [[10,20],[30,200],[400,50],[30,20]]110

Constraints#

  • 2 * n people, 1 <= n <= 100.

Approach#

Sort by cost[0] - cost[1] ascending. The first n go to A (they have the biggest A-discount); the rest go to B.

Solution#

Two City Scheduling
class Solution {
public:
int twoCitySchedCost(vector<vector<int>>& costs) {
sort(costs.begin(), costs.end(), [](auto& a, auto& b){
return a[0] - a[1] < b[0] - b[1];
});
int total = 0, n = costs.size() / 2;
for (int i = 0; i < (int)costs.size(); ++i) {
total += i < n ? costs[i][0] : costs[i][1];
}
return total;
}
};

Editorial#

Exchange argument: imagine assigning A to person i and B to person j. Total = a_i + b_j. Swapping yields a_j + b_i. The swap saves (a_i - b_i) - (a_j - b_j). We prefer the assignment with smaller a - b going to A — exactly the sort key.

Complexity#

  • Time: O(n log n).
  • Space: O(1).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.