公司计划面试 2N 人。第 i 人飞往 A 市的费用为 costs[i][0],飞往 B 市的费用为 costs[i][1]。
返回将每个人都飞到某座城市的最低费用,要求每个城市都有 N 人抵达。
- 示例:
输入:[[10,20],[30,200],[400,50],[30,20]]
输出:110
只处理偶数版:
def twoCitySchedCost(costs):
costs.sort(key=lambda x:x[0]-x[1])
total = 0
n = len(costs)//2
for i in range(n):
total += costs[i][0] + costs[i+n][1]
return total
ret2 = twoCitySchedCost([[10, 20], [30, 200], [400, 50], [30, 20]])
print(ret2)
奇偶包容版:
def twoCitySchedCost(costs):
costs.sort(key=lambda x: x[0] - x[1])
total = 0
con = len(costs)
if len(costs) % 2 == 0:
n = con // 2
for i in range(n):
total += costs[i][0] + costs[con - (1 + i)][1]
else:
n = (con - 1) // 2
for i in range(n):
total += costs[i][0] + costs[2 * n - i][1]
total += min(costs[n][0], costs[n][1])
return total
ret2 = twoCitySchedCost([[10, 20], [30, 200], [400, 50], [30, 20], [100, 40]])
print(ret2)