Two City Scheduling
Send 2n people half to A, half to B minimizing total cost — sort by cost difference.
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 * npeople,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#
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; }};import "sort"
func twoCitySchedCost(costs [][]int) int { sort.Slice(costs, func(i, j int) bool { return costs[i][0]-costs[i][1] < costs[j][0]-costs[j][1] }) total, n := 0, len(costs)/2 for i, c := range costs { if i < n { total += c[0] } else { total += c[1] } } return total}from typing import List
class Solution: def twoCitySchedCost(self, costs: List[List[int]]) -> int: costs.sort(key=lambda c: c[0] - c[1]) n = len(costs) // 2 total = 0 for i, c in enumerate(costs): total += c[0] if i < n else c[1] return totalvar twoCitySchedCost = function(costs) { costs.sort((a, b) => (a[0] - a[1]) - (b[0] - b[1])); const n = costs.length / 2; let total = 0; for (let i = 0; i < costs.length; i++) { total += i < n ? costs[i][0] : costs[i][1]; } return total;};class Solution { public int twoCitySchedCost(int[][] costs) { Arrays.sort(costs, (a, b) -> (a[0] - a[1]) - (b[0] - b[1])); int n = costs.length / 2; int total = 0; for (int i = 0; i < costs.length; i++) { total += i < n ? costs[i][0] : costs[i][1]; } return total; }}function twoCitySchedCost(costs: number[][]): number { costs.sort((a: number[], b: number[]) => (a[0] - a[1]) - (b[0] - b[1])); const n: number = costs.length / 2; let total: number = 0; for (let i = 0; i < costs.length; 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#
Related#