Two City Scheduling
https://leetcode.com/contest/weekly-contest-133/problems/two-city-scheduling/
一个数组,每个元素有两个数,问其中一半取第一个,另一半取第二个,能使得总和最小,此时和是多少。
There are
2N
people a company is planning to interview. The cost of flying thei
-th person to cityA
iscosts[i][0]
, and the cost of flying thei
-th person to cityB
iscosts[i][1]
.Return the minimum cost to fly every person to a city such that exactly
N
people arrive in each city.Example 1:
Note:
1 <= costs.length <= 100
It is guaranteed that
costs.length
is even.
1 <= costs[i][0], costs[i][1] <= 1000
Thoughts
假设A取的都是first, 那么A是想取first和sec中尽量都是first小的,也就是每个单独能max(sec - first)的。同理B是想取max(f - s), 也就是min(sec - first)。因此对first-sec排序,前一半归A, 后一半归B. a[0] - a[1] < b[0] - b[1] => a[0] + b[1] < a[1] + b[0] 意味着a去0b去1比a去1比b去0好。当有多个元素时,前一半去A后一半去B比任意调换其中顺序的结果好。
Last updated
Was this helpful?