对于一个人来说,他必定要去往A城市或者B城市,去往A城市的对比去往B城市的收益为两者之差,收益最大化就是最终结果的最小化。
计算一个gap矩阵为去往A城市和去往B城市费用之差,对gap矩阵排序获得idx,前N/2的人去往A城市,后N/2的人去往B城市。
细节: 数组排序获得index: idx = sorted(range(len(array)), key=lambda i:array[i])
class Solution(object):
def twoCitySchedCost(self, costs):
"""
:type costs: List[List[int]]
:rtype: int
"""
if not costs:
return 0
gap = []
for i in range(len(costs)):
gap.append(costs[i][0] - costs[i][1])
idx = sorted(range(len(gap)), key=lambda i: gap[i])
res = 0
for i in idx[:len(idx)//2]:
res += costs[i][0]
for i in idx[len(idx)//2:]:
res += costs[i][1]
return res
网友评论