Two City Scheduling - Problem

A company is planning to interview 2n people. Given the array costs where costs[i] = [aCosti, bCosti], the cost of flying the i-th person to city a is aCosti, and the cost of flying the i-th 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.

Input & Output

Example 1 — Basic Case
$ Input: costs = [[10,20],[30,200],[400,50],[30,20]]
Output: 110
💡 Note: First person to city A (cost 10), second to city A (cost 30), third to city B (cost 50), fourth to city B (cost 20). Total: 10+30+50+20 = 110
Example 2 — Different Assignment
$ Input: costs = [[259,770],[448,54],[926,667],[184,139],[840,118],[577,469]]
Output: 1859
💡 Note: Optimal assignment sends 3 people to each city based on cost differences, minimizing total expense
Example 3 — Equal Costs
$ Input: costs = [[10,10],[20,20]]
Output: 30
💡 Note: When costs are equal for both cities, any assignment gives same total: 10+20 = 30

Constraints

  • 2 * n == costs.length
  • 2 ≤ costs.length ≤ 100
  • costs.length is even
  • 1 ≤ aCosti, bCosti ≤ 1000

Visualization

Tap to expand
Two City Scheduling - Greedy Approach INPUT costs[i] = [aCost, bCost] Person 0: 10 20 Person 1: 30 200 Person 2: 400 50 Person 3: 30 20 City A City B n = 2 people per city ALGORITHM STEPS 1 Calculate Difference diff = aCost - bCost P0: 10-20 = -10 P1: 30-200 = -170 P2: 400-50 = 350 P3: 30-20 = 10 Negative: prefer A | Positive: prefer B 2 Sort by Difference Ascending order P1(-170), P0(-10), P3(10), P2(350) 3 Assign Cities First n to A, rest to B 4 Sum Costs Total = 30 + 10 + 20 + 50 FINAL RESULT City A (n=2) Person 1: $30 Person 0: $10 City B (n=2) Person 3: $20 Person 2: $50 Cost Breakdown City A: 30 + 10 = 40 City B: 20 + 50 = 70 Total: 40 + 70 = 110 OUTPUT 110 OK - Minimum Cost Achieved! Key Insight: Sort people by (aCost - bCost). Negative difference means person strongly prefers City A. Send first n people (lowest differences) to City A, remaining n to City B. Time: O(n log n) for sorting | Space: O(1) or O(n) depending on sort implementation. TutorialsPoint - Two City Scheduling | Greedy - Sort by Cost Difference
Asked in
Amazon 15 Google 8 Microsoft 6
178.0K Views
Medium Frequency
~15 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen