[LeetCode] 1029. Two City Scheduling

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.

Example 2:

Input: costs = [[259,770],[448,54],[926,667],[184,139],[840,118],[577,469]]
Output: 1859

Example 3:

Input: costs = [[515,563],[451,713],[537,709],[343,819],[855,779],[457,60],[650,359],[631,42]]
Output: 3086 

Constraints:

  • 2 * n == costs.length
  • 2 <= costs.length <= 100
  • costs.length is even.
  • 1 <= aCosti, bCosti <= 1000

两地调度。

公司计划面试 2n 人。给你一个数组 costs ,其中 costs[i] = [aCosti, bCosti] 。第 i 人飞往 a 市的费用为 aCosti ,飞往 b 市的费用为 bCosti 。

返回将每个人都飞到 a 、b 中某座城市的最低费用,要求每个城市都有 n 人抵达

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/two-city-scheduling
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路是贪心,我这里直接翻译一下LC discussion的最高票答案好了,同时参考题干中的例子。

costs = [[10,20],[30,200],[400,50],[30,20]]

假设如果把所有的人都安排去 A 地参加面试,那么花费是 cost = 10 + 30 + 400 + 30 = 470。但是因为题目要求需要送一半的人去 B 地面试,那么现在需要选择送什么人去 B 地呢?可以这样想,既然我目前已经花了 470 块送所有人去 A 地面试,那么我每送一个人去 B 地我会得到来自 A 地的退款。按照这个思路,应该是去检查如何安排才能使来自 A 地的退款更多。计算退款 refund 的方式是

refund[i] = 0 - cost[i][0] + cost[i][1] - 意思是我可以得到 A 地的退款,但是也需要加上去 B 地的花费

得到数组 refund = [10, 170, -350, -10]

这里每个数字,如果是正数则说明我们需要额外付钱,如果是负数说明可以得到退款。接下来对 refund 数组排序,得到 refund = [-350, -10, 10, 170],如果按照这个逻辑去安排,则最小花费是一开始的 470 - 350 - 10 = 110块。

时间O(nlogn) - sort

空间O(n)

Java实现

 1 class Solution {
 2     public int twoCitySchedCost(int[][] costs) {
 3         int n = costs.length;
 4         int sum = 0;
 5         // the cost for everyone to fly to city A
 6         for (int i = 0; i < n; i++) {
 7             sum += costs[i][0];
 8         }
 9 
10         int[] refund = new int[n];
11         for (int i = 0; i < n; i++) {
12             refund[i] = 0 - costs[i][0] + costs[i][1];
13         }
14         Arrays.sort(refund);
15         for (int i = 0; i < n / 2; i++) {
16             sum += refund[i];
17         }
18         return sum;
19     }
20 }

 

LeetCode 题目总结

posted @ 2020-06-04 14:49  CNoodle  阅读(222)  评论(0编辑  收藏  举报