Two City Scheduling

Send half of the people to city A and half to city B so that the total ticket cost is as small as possible.

A company is flying 2n people to a meeting, and each person can go to city A or to city B. The array costs has one row per person, [aCost, bCost]: the price of flying that person to city A and the price of flying them to city B. Exactly n people must go to each city. Return the lowest possible total cost.

Example 1
Input: costs = [[10, 20], [30, 200], [400, 50], [30, 20]]
Output: 110
Explanation: persons 0 and 1 fly to A (10 + 30), persons 2 and 3 fly to B (50 + 20).
Example 2
Input: costs = [[259, 770], [448, 54], [926, 667], [184, 139], [840, 118], [577, 469]]
Output: 1859
Solution

The Idea

Picture someone booking travel for a group. Each traveller can be sent to one of two cities, the ticket prices differ from person to person, and both cities must get the same number of visitors. The goal is the cheapest set of tickets that keeps the two groups equal.

Look at Example 1. Person 0 pays 10 to fly to A and 20 to fly to B, while person 2 pays 400 for A but only 50 for B. If everyone could simply take their cheaper ticket, the answer would be easy. Example 2 shows why that fails: only person 0 is cheaper in A (259 against 770), so five people would land in B and one in A. The equal halves are what make the problem hard. So which n people should go to A?

Start from a plan that ignores the halves: send everyone to B. In Example 1 that costs 20 + 200 + 50 + 20 = 290. Now move people to A one at a time. Moving person 1 swaps a ticket of 200 for a ticket of 30, so the total changes by 30 - 200 = -170. Moving person 2 changes it by 400 - 50 = +350. Each person's change is just aCost - bCost, and it does not depend on who else moves.

Look at the picture below. The four people are sorted by the column labelled "change if moved to A", smallest first.

Example 1 sorted by the change if moved to A: person 1 at -170, person 0 at -10, person 3 at +10, person 2 at +350. Persons 1 and 0 move to A, persons 3 and 2 stay in B. Everyone in B costs 290, and 290 - 170 - 10 = 110.

Exactly two people must move, and each move adds its own change to 290. To end with the smallest total, move the two people with the smallest changes, person 1 at -170 and person 0 at -10, the two orange rows marked "moves to A". The last line of the picture gives the result: 290 - 170 - 10 = 110. Person 3 would add 10 by moving and person 2 would add 350, so both stay in B.

So the choice between two cities turns into one number per person, and the whole problem becomes: sort the people by that number and send the first half to A.

Solution Approach

Turning that idea into code means settling three things: why trying every split is too slow, which value to sort the people by, and why the first half after sorting is never worse than any other split.

Trying every split

Why not try every way of choosing n people for A? Example 2 has 6 people, and there are 20 ways to choose 3 of them, which is quick to check. But the count grows fast: 20 people already give 184,756 ways, and each one needs its own sum. A single sort avoids all of that.

Sorting by the cost difference

Which value should the sort compare? For each person it is aCost - bCost, the change in the total if that person flies to A instead of B. A negative change means A is cheaper for that person, and the more negative, the bigger the saving. Java's Arrays.sort can sort the rows of costs with a comparator, a small function that says which of two rows comes first. Here it compares the two differences:

Java
Arrays.sort(costs, (a, b) -> Integer.compare(a[0] - a[1], b[0] - b[1]));

Why the first half is the cheapest

Is the first half really the best choice? Suppose some split sends person x to A and person y to B, but y has the smaller change. Swap them: x returns to B and y moves to A. Both cities still hold n people, and the total changes by y's change minus x's change, which is zero or less.

Repeating such swaps reaches the sorted split without ever raising the total, so the sorted split is as cheap as any other. Taking the people who save the most by flying to A, one after another, without ever trying another combination, is called a greedy choice. The swap shows that this greedy choice is safe for two cities.

Java Solution

The method twoCitySchedCost works in these steps:

  1. First, sort the rows of costs with Arrays.sort and a comparator on aCost - bCost, so the person who saves the most by flying to A comes first.
  2. Set n to costs.length / 2, the number of people each city gets, and start total at 0.
  3. Walk over the sorted rows with one loop and index i. For the first n rows, add the A price costs[i][0] to total; for the rest, add the B price costs[i][1].
  4. After the last row, return total, the cheapest cost of the whole trip.

The main method runs both examples, two people who both prefer B, four people who all prefer A, and then prints Example 1's array again after the call.

Java
import java.util.Arrays;

public class TwoCityScheduling {

    public static int twoCitySchedCost(int[][] costs) {
        // Sort by the change in total if the person flies to A instead of B.
        Arrays.sort(costs, (a, b) -> Integer.compare(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];   // first half to A, second half to B
        }
        return total;
    }

    public static void main(String[] args) {
        System.out.println(twoCitySchedCost(new int[][] {
                {10, 20}, {30, 200}, {400, 50}, {30, 20}}));
        System.out.println(twoCitySchedCost(new int[][] {
                {259, 770}, {448, 54}, {926, 667}, {184, 139}, {840, 118}, {577, 469}}));
        System.out.println(twoCitySchedCost(new int[][] {{5, 1}, {6, 1}}));
        System.out.println(twoCitySchedCost(new int[][] {{1, 100}, {2, 100}, {3, 100}, {4, 100}}));
        int[][] costs = {{10, 20}, {30, 200}, {400, 50}, {30, 20}};
        twoCitySchedCost(costs);
        System.out.println(Arrays.deepToString(costs));
    }
}

Running it prints:

Output
110
1859
6
203
[[30, 200], [10, 20], [30, 20], [400, 50]]

110 and 1859 match the two examples. In Example 2, the three smallest changes belong to person 0 (-511), person 3 (+45) and person 5 (+108). Those three fly to A for 259 + 184 + 577 = 1020, and the other three fly to B for 54 + 667 + 118 = 839, which makes 1859.

The 6 comes from [[5, 1], [6, 1]]. Both people would rather pay 1 for B, but one of them has to go to A, and the sort picks the cheaper A ticket, 5, so the total is 5 + 1. The 203 is the same rule the other way round: all four people find A cheaper, yet two must go to B. The two with A prices of 3 and 4 lose the least by moving, so they pay 100 each: 1 + 2 + 100 + 100 = 203.

The last line shows a side effect. Arrays.sort reorders the caller's array in place, so Example 1's array now starts with [30, 200], person 1 with the change of -170. A caller who needs the original order can pass a copy made with costs.clone(), which the sort reorders while the original array stays as it was.

Complexity

Nearly all the work is the sort; the loop after it reads each row once.

  • Time: O(n log n), because sorting the 2n rows by their cost difference takes O(2n log 2n) steps, which is O(n log n), and the loop that adds up the tickets visits each of the 2n rows once.
  • Space: O(n), because Arrays.sort on the int[] rows uses a merge-based sort called TimSort, which can need temporary room for up to half of the rows. The method itself keeps only n, total and i.

Assign Cookies is another problem solved by sorting first and then making a single pass.