Problem Description
Given 2n people and their respective costs for traveling to two cities A and B, find the minimum total cost to send exactly n people to each city. Each person has a cost profile [aCost, bCost] representing the cost of sending them to city A or city B.
Key Insights
- Sort the cost array based on the difference (aCost - bCost).
- Sending a person to city A saves money when aCost is much lower than bCost, and vice versa.
- By sorting the array, the optimal decision is to send the first n people (with greatest relative savings for city A) to city A and the remaining n people to city B.
- The greedy approach minimizes total cost by maximizing cost differences.
Space and Time Complexity
Time Complexity: O(n log n) due to sorting the array of 2n elements. Space Complexity: O(1) if in-place sorting is allowed, otherwise O(n) for the sorted array copy.
Solution
The solution uses a greedy algorithm. First, we compute the difference between the cost of going to city A and city B for each person. We sort the list of costs based on this difference. The intuition is that if a person is much cheaper to send to city A than to city B (i.e., a very negative difference), they should go to city A. Conversely, if the cost for city B is significantly lower, they should be allocated there. After sorting, we assign the first n people to city A and the remaining n people to city B, ensuring that the balance of people in each city is maintained. This approach guarantees that the total cost is minimized.