Problem
A company is planning to interview 2n
people. Given the array costs
where costs[i] = [aCosti, bCosti]
, the cost of flying the ith
person to city a
is aCosti
, and the cost of flying the ith
person to city b
is bCosti
.
Return the minimum cost to fly every person to a city such that exactly n
people arrive in each city.
Examples
Example 1:
|
|
Example 2:
|
|
Example 3:
|
|
Solution
First example is kind of misleading, as we take min
of city A and B, then each person is going to respective city. We are interested in overall min cost for the company, and half of people should go to A and half to B.
So, 1 solution is backtracking as a brute force solution. And as we want min cost, then DP can also help, but there is a greedy solution as well.
Method 1 - Greedy Using Cost Difference
Lets assume we send all persons to city A.
The idea is to send each person to city A.
|
|
So, totalCost = 10 + 30 + 400 + 30 = 470
Now, we need to send n persons to city B. Which persons do we need to send city B?
Here, we need to minimize the cost.
Now, we have already paid money to go to city A. So, Send the persons to city B who get more refund so that our cost will be minimized.
So, maintain refunds of each person,
|
|
So, refunds of each person
|
|
Here, refund +ve means we need to pay, -ve means we will get refund.
So, sort the refund array.
|
|
Now, get refund for N persons,
|
|
So, minimum cost is 110
Code
|
|
Complexity
- ⏰ Time complexity:
O(n log n)
- O(n) to compute the initial cost and refund array.
- O(n log n) to sort the refund array.
- O(n) to sum the N smallest refunds.
- Overall: O(n log n) (sorting dominates).
- 🧺 Space complexity:
O(n)
- O(n) for the refund array.
- O(1) extra space otherwise (ignoring input and output).