The company plans to interview 2N people. The cost of the i-th person flying to city A is costs[i][0], and the cost of flying to city B is costs[i][1].
Returning to the minimum cost of flying everyone to a certain city requires N people to arrive in each city.
Example:
Input: [[10,20],[30,200],[400,50],[30,20]]
Output: 110
Explanation: The
first person goes to city A, the cost is 10.
The second person goes to City A at a cost of 30.
The third person goes to city B at a cost of 50.
The fourth person goes to city B at a cost of 20.
The minimum total cost is 10 + 30 + 50 + 20 = 110, and half of the people in each city are interviewing.
prompt:
1 <= costs.length <= 100
costs.length 为偶数
1 <= costs[i][0], costs[i][1] <= 1000
Source: LeetCode
Link: https://leetcode-cn.com/problems/two-city-scheduling The
copyright is owned by LeetCode . For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.
ps: I wrote two questions when I was bored waiting for the flight, and the ideas for these questions are all in the annotation
class Solution {
public int twoCitySchedCost(int[][] costs) {
//先把全部人都去a市,然后再让一半的人去b市,什么人去b市呢,就是去a市不省钱的人(没有进入省钱排行榜前一半)
//a[0]-a[1]就是看是不是去a市更省钱,再减去(b[0]-b[1])就是看谁更省钱谁就留在A市
Arrays.sort(costs,(a,b)->(a[0]-a[1]-(b[0]-b[1])) );
// Arrays.sort(costs, new Comparator<int[]>() {
// @Override
// public int compare(int[] o1, int[] o2) {
// return o1[0] - o1[1] - (o2[0] - o2[1]);
// }
// });
int total = 0;
int n = costs.length / 2;
//前一半的人留在a市后一半的人去b市
for (int i = 0; i < n; ++i) total += costs[i][0] + costs[i + n][1];
return total;
}
}