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: Minimize Total Flight CostsInput: costs = [[10,20],[30,200],[400,50],[30,20]]Person 0Person 1Person 2Person 3[10,20][30,200][400,50][30,20]City ACity BP0: 10, P1: 30P2: 50, P3: 20Total Cost: 10 + 30 + 50 + 20 = 110✓ Exactly 2 people in each city
Understanding the Visualization
1
Input
2n people with flight costs to cities A and B
2
Process
Calculate cost differences and sort by savings
3
Output
Minimum total cost with n people in each city
Key Takeaway
🎯 Key Insight: Sort people by cost difference (A-B) and assign greedily to minimize total expense
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