A company is planning to interview 2n people. Given the array costs where costs[i] = [aCosti, bCosti], the cost of flying the ith person to city a is aCosti, and the cost of flying the ith 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.
给一个2n x 2的数组costs,其中costs[ i ] 为第 i 个人 到城市A 和 到城市B 的cost,即costs[ i ] = [costA, costB]。
要把这2n个人中的n个送到A, 另外n个送到B,问最小cost。
思路:
2n个人要对半分,n个去A,n个去B。
把 costA比costB小 的放在数组左边,costA比costB大 的放在数组右边。
涉及到了排序。
按什么排?按costA - costB排,也就是按costs[ i ][0] - costs[ i ][ 1 ]排序。
排好序后前半段加costA,后半段加costB。
public int twoCitySchedCost(int[][] costs) {
int n = costs.length / 2;
int result = 0;
int cnt = 0;
Arrays.sort(costs, (a, b) -> (a[0] - a[1] - b[0] + b[1]));
for(int[] cost : costs) {
if(cnt < n) {
result += cost[0];
} else {
result += cost[1];
}
cnt ++;
}
return result;
}