Brute force
Try flying each person to city A and city B and take the minimum cost.
Time: , space:
.
class Solution:
def explore(self, i, costs, first_count, second_count, curr_cost):
if i == len(costs):
if first_count == second_count:
return curr_cost
return float("inf")
return min(
self.explore(i+1, costs, first_count+1, second_count, curr_cost+costs[i][0]),
self.explore(i+1, costs, first_count, second_count+1, curr_cost+costs[i][1])
)
def twoCitySchedCost(self, costs: List[List[int]]) -> int:
return self.explore(0, costs, 0, 0, 0)
Greedy
For a cost pair , when we decide to fly a person to city A, we are also deciding to not fly that person to city B. We have to optimize both of these sub-decisions: minimize
and maximize
. Minimizing the cost differential
achieves both.
For example, between two cost pairs: and
, although
we would prefer flying a person to city A with cost
because that would eliminate the super expensive choice of
. So, total cost would be
instead of
.
Time: , space:
.
class Solution:
def twoCitySchedCost(self, costs: List[List[int]]) -> int:
costs.sort(key=lambda pair: pair[0] - pair[1])
n = len(costs) // 2
return sum(costs[i][0] for i in range(n)) + sum(costs[i][1] for i in range(n, len(costs)))
Leave a comment