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[aCost, bCost]
Example 1
Output: 110
Explanation: persons 0 and 1 fly to A (10 + 30), persons 2 and 3 fly to B (50 + 20).
Example 2
Output: 1859
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
Look at the picture below. The four people are sorted by the column labelled "change if moved to A", smallest first.
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 - bCostArrays.sortcosts
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
- First, sort the rows of
withcosts and a comparator onArrays.sort , so the person who saves the most by flying to A comes first.aCost - bCost - Set
ton , the number of people each city gets, and startcosts.length / 2 at 0.total - Walk over the sorted rows with one loop and index
. For the firsti rows, add the A pricen tocosts[i][0] ; for the rest, add the B pricetotal .costs[i][1] - After the last row, return
, the cheapest cost of the whole trip.total
The main
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:
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]]
The last line shows a side effect. Arrays.sort[30, 200]costs.clone()
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
on theArrays.sort rows uses a merge-based sort called TimSort, which can need temporary room for up to half of the rows. The method itself keeps onlyint[] ,n andtotal .i