Sponsored
Sponsored
This approach relies on sorting the people by the difference between the cost of flying them to city A and city B. By doing so, we can initially assume that flying every person to city A is optimal, and then we adjust half of the people to go to city B based on minimal added cost.
The time complexity of this solution is O(n log n) due to the sorting step, and the space complexity is O(1) since we are sorting in place.
1def twoCitySchedCost(costs):
2 costs.sort(key=lambda cost: cost[0] - cost[1])
3 n = len(costs) // 2
4 totalCost = sum(cost[0] for cost in costs[:n]) + sum(cost[1] for cost in costs[n:])
5 return totalCost
Python's solution sorts the list using the custom key which is the cost difference between city A and city B. The total cost is then computed by summing the cheaper city for the suitable half of the sorted list.