Leetcode 1029: Two City Scheduling

grid47
grid47
Exploring patterns and algorithms
Jul 27, 2024 5 min read

A company is planning to interview 2n people, and for each person, there are two possible cities where they can be interviewed. The cost of flying a person to city A or city B is given. You need to find the minimum cost to fly exactly n people to each city. The challenge is to select n people for city A and the remaining n people for city B such that the total cost is minimized.
Problem
Approach
Steps
Complexity
Input: The input consists of a 2D array where each element costs[i] = [aCosti, bCosti], representing the cost of flying the i-th person to city A and city B, respectively.
Example: costs = [[10,20],[30,200],[400,50],[30,20]]
Constraints:
• 2 <= costs.length <= 100
• costs.length is even
• 1 <= aCosti, bCosti <= 1000
Output: The output is the minimum total cost to fly n people to each city.
Example: Output: 110
Constraints:
• The total number of people is even, so exactly half will be sent to each city.
Goal: The goal is to minimize the total cost of flying exactly n people to each city while considering both possible costs for each person.
Steps:
• 1. For each person, calculate the difference in cost between flying them to city A and flying them to city B.
• 2. Accumulate the cost for flying everyone to city A initially.
• 3. Sort the differences in cost (refunds) and select the smallest n differences to add to the total cost, representing the people who will be sent to city B.
• 4. Return the final accumulated cost.
Goal: Ensure the solution efficiently handles the constraints, especially when the number of people is large.
Steps:
• The solution must run efficiently for input arrays up to 100 elements.
Assumptions:
• The number of people is always even, and half of them must go to each city.
Input: Input: costs = [[10,20],[30,200],[400,50],[30,20]]
Explanation: The optimal way is to send the first two people to city A with costs 10 and 30, and the last two to city B with costs 50 and 20. The minimum total cost is 10 + 30 + 50 + 20 = 110.

Input: Input: costs = [[259,770],[448,54],[926,667],[184,139],[840,118],[577,469]]
Explanation: Here, the optimal solution gives a total cost of 1859, balancing between the lower costs for each city.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus