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
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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code