1029. Two City Scheduling
Problem
Tags: Array, Greedy, Sorting
A company is planning to interview 2n people. Given the array costs where costs[i] = [aCosti, bCosti], the cost of flying the i^th person to city a is aCosti, and the cost of flying the i^th person to city b is bCosti.
Return the minimum cost to fly every person to a city such that exactly n people arrive in each city.
Example 1:
Input: costs = [[10,20],[30,200],[400,50],[30,20]]
Output: 110
Explanation: 
The first person goes to city A for a cost of 10.
The second person goes to city A for a cost of 30.
The third person goes to city B for a cost of 50.
The fourth person goes to city B for a cost of 20.
The total minimum cost is 10 + 30 + 50 + 20 = 110 to have half the people interviewing in each city.
Example 2:
Input: costs = [[259,770],[448,54],[926,667],[184,139],[840,118],[577,469]]
Output: 1859
Example 3:
Input: costs = [[515,563],[451,713],[537,709],[343,819],[855,779],[457,60],[650,359],[631,42]]
Output: 3086
Constraints:
2 * n == costs.length2 <= costs.length <= 100costs.lengthis even.1 <= aCosti, bCosti <= 1000
Code
C
// 1029. Two City Scheduling (10/2/54199)
// Runtime: 2 ms (78.20%) Memory: 6.03 MB (63.53%) 
int comp(int* a[], int* b[]) {
    return ((*a)[0] - (*a)[1]) - ((*b)[0] - (*b)[1]);
}
int twoCitySchedCost (int* costs[], int costs_size, int* costs_col_size) {
    qsort(costs, costs_size, sizeof(int*), &comp);
    
    int total = 0;
    int half = costs_size / 2;
    
    for (int i = 0; i < half; i++) {
        total += costs[i][0];
    }
    for (int i = half; i < costs_size; i++) {
        total += costs[i][1];
    }
    
    return total;
}
JS
// 1029. Two City Scheduling (10/13/54199)
// Runtime: 65 ms (77.25%) Memory: 42.04 MB (77.59%) 
/**
 * @param {number[][]} costs
 * @return {number}
 */
function twoCitySchedCost(costs) {
    costs.sort((a, b) => (a[0] - a[1]) - (b[0] - b[1]));
    return costs.reduce((sum, cost, i) => sum + cost[0 + (i >= costs.length / 2)], 0);
};
TS
// 1029. Two City Scheduling (10/14/54199)
// Runtime: 111 ms (25.16%) Memory: 44.16 MB (76.13%) 
function twoCitySchedCost(costs: number[][]): number {
    costs.sort((a: number[], b: number[]) => (a[0] - a[1]) - (b[0] - b[1]));
    return costs.reduce((sum, cost, i) => sum + cost[i >= costs.length / 2 ? 1 : 0], 0);
};