标签:refund City 10 int 30 1029 cost Scheduling city
There are 2N
people a company is planning to interview. The cost of flying the i
-th person to city A
is costs[i][0]
, and the cost of flying the i
-th person to city B
is costs[i][1]
.
Return the minimum cost to fly every person to a city such that exactly N
people arrive in each city.
Example 1:
Input: [[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.
Note:
1 <= costs.length <= 100
- It is guaranteed that
costs.length
is even. 1 <= costs[i][0], costs[i][1] <= 1000
两地调度。提议是给你一个长度为2N的二维数组代表有2N个人需要去A,B两地面试的路费cost,请做一下安排使得AB两地面试人数相同且路费最小。
思路是贪心,我这里直接翻译一下LC discussion的最高票答案好了,同时参考题干中的例子。
costs = [[10,20],[30,200],[400,50],[30,20]]
首先假设,如果把所有的人都安排去A地参加面试,那么会得到cost = 10 + 30 + 400 + 30 = 470。但是因为题目要求需要送一半的人去B地面试,那么现在需要选择送什么人去B地呢?可以这样想,既然我目前已经花了470块送所有人去A地面试,那么我每送一个人去B地我都算是赚到了,因为我会得到来自A地的退款。按照这个思路,应该是去检查如何安排才能使退款更多。计算退款refund的方式是
refund[i] = cost[i][1] - cost[i][0]
得到数组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 / 2; 4 int[] refund = new int[N * 2]; 5 int minCost = 0; 6 int index = 0; 7 for (int[] cost : costs) { 8 refund[index++] = cost[1] - cost[0]; 9 minCost += cost[0]; 10 } 11 Arrays.sort(refund); 12 for (int i = 0; i < N; i++) { 13 minCost += refund[i]; 14 } 15 return minCost; 16 } 17 }
标签:refund,City,10,int,30,1029,cost,Scheduling,city 来源: https://www.cnblogs.com/cnoodle/p/13043535.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。