Algo-Sim › Greedy

Two City Scheduling

Medium · Greedy · step through it in Java, Python and C++ on your own input

Fly half the people to city A and half to B as cheaply as possible: sort by costA − costB and send the first half to A.

Problem

A company is interviewing 2n people. costs[i] = [aCost, bCost] is the cost of flying person i to city A or to city B. Return the minimum total cost such that exactly n people arrive in each city.

Constraints

Edge cases to test

Follow-up questions

Why sort by costA − costB?
Sending someone to A instead of B costs that difference; the n most negative differences save the most. O(n log n).
Can you avoid a full sort?
Quickselect the n-th smallest difference: O(n) on average.

Solution

Java

public int twoCitySchedCost(int[][] costs) {
    // Sending someone to A instead of B costs costA - costB extra.
    Arrays.sort(costs, (a, b) -> (a[0] - a[1]) - (b[0] - b[1]));
    int n = costs.length / 2, total = 0;
    for (int i = 0; i < 2 * n; i++)
        total += i < n ? costs[i][0] : costs[i][1];
    return total;
}

Python

def two_city_sched_cost(costs):
    # Sending someone to A instead of B costs cost_a - cost_b extra.
    costs = sorted(costs, key=lambda c: c[0] - c[1])
    n, total = len(costs) // 2, 0
    for i, (a, b) in enumerate(costs):
        total += a if i < n else b
    return total

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    int twoCitySchedCost(vector<vector<int>> &costs) {
        // Sending someone to A instead of B costs costA - costB extra.
        sort(costs.begin(), costs.end(), [](auto &a, auto &b) { return a[0] - a[1] < b[0] - b[1]; });
        int n = int(costs.size()) / 2, total = 0;
        for (int i = 0; i < 2 * n; i++)
            total += i < n ? costs[i][0] : costs[i][1];
        return total;
    }
};

More Greedy problems