Two City Scheduling

medium array greedy sorting

Problem

Given 2n people where costs[i] = [costA, costB] (the cost to fly person i to city A or city B), return the minimum total cost when exactly n people go to each city.

Inputcosts = [[10,20],[30,200],[400,50],[30,20]]
Output110
Sort by (A − B). Send the 2 cheapest-A-relatively to A, others to B.

def two_city_sched_cost(costs):
    costs.sort(key=lambda c: c[0] - c[1])
    n = len(costs) // 2
    total = 0
    for i, (a, b) in enumerate(costs):
        total += a if i < n else b
    return total
function twoCitySchedCost(costs) {
  costs.sort((x, y) => (x[0] - x[1]) - (y[0] - y[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, (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;
    }
}
int twoCitySchedCost(vector<vector<int>>& costs) {
    sort(costs.begin(), costs.end(), [](auto& x, auto& y) {
        return (x[0] - x[1]) < (y[0] - y[1]);
    });
    int n = costs.size() / 2, total = 0;
    for (int i = 0; i < (int)costs.size(); i++) {
        total += i < n ? costs[i][0] : costs[i][1];
    }
    return total;
}
Time: O(n log n) Space: O(1)