我们这样来看这个问题,公司首先将这 2N2N 个人全都安排飞往 BB 市,
再选出 NN 个人改变它们的行程,让他们飞往 AA 市。如果选择改变一个人的行程,
那么公司将会额外付出 price_A - price_B 的费用,这个费用可正可负
因此最优的方案是,
选出 price_A - price_B 最小的 NN 个人,
让他们飞往 A 市,其余人飞往 B 市。
算法:
按照 price_A-proice_B从小到大排序
将前N个飞往A世,其余人飞往B世,并计算出总费用
public int twoCitySchedCost(int[][] costs) {
//对数组进行排序
//自行定义比较器
Arrays.sort(costs, new Comparator<int[]>() {
@Override
public int compare(int[] o1, int[] o2) {
return (o1[0]-o1[1]-(o2[0]-o2[1]));
}
});
//前N个人选择
int N = costs.length/2;
int cost = 0;
for(int i=0;i<costs.length;i++){
cost=costs[i][0]+costs[i+N][1];
}
return cost;
}