LeetCode 1029
有两个城市,每个城市都要分配N个人,要使得成本最少,那么就要先选那些两者差价最大的城市里面取价格小的那个。如果取满其中的N个之后,我们只能选其他的城市。
def twoCitySchedCost(self, costs: List[List[int]]) -> int:
#按照差价大小倒序排列
sortedCosts = sorted(costs, key=lambda x: abs(x[0]-x[1]), reverse=True)
A = len(costs)//2
B = A
total = 0
for c in sortedCosts:
#两个城市都没有满,总是取价格小的一个
if A > 0 and B > 0:
if c[0] > c[1]:
total += c[1]
B-=1
else:
total += c[0]
A-=1
#A没有满,全部取A
elif A > 0:
total +=c[0]
A-=1
#B没有满,那么就全部取B
elif B > 0:
total +=c[1]
B-=1
return total