思路:将所有人飞往 a 市的费用与飞往 b 市的费用之差作为一个人的代价,然后将这些代价按照从小到大排序,选取前 n 个代价作为所有人飞往 a 市的最小代价,剩下的代价作为所有人飞往 b 市的最小代价。最后将两个代价相加即为总费用。

Java 代码:

class Solution { public int twoCitySchedCost(int[][] costs) { int n = costs.length / 2; int[] diff = new int[costs.length]; int sum = 0; for (int i = 0; i < costs.length; i++) { diff[i] = costs[i][0] - costs[i][1]; sum += costs[i][1]; } Arrays.sort(diff); for (int i = 0; i < n; i++) { sum += diff[i]; } return sum; }

Java 实现 公司计划面试 2n 人。给你一个数组 costs 其中 costsi = aCosti bCosti 。第 i 人飞往 a 市的费用为 aCosti 飞往 b 市的费用为 bCosti 。返回将每个人都飞到 a 、b 中某座城市的最低费用要求每个城市都有 n 人抵达。

原文地址: https://www.cveoy.top/t/topic/gBr1 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录