Two City Scheduling
Master this topic with zero to advance depth.
Two City Scheduling
A company is planning to interview 2n people. Given the array costs where costs[i] = [aCost_i, bCost_i], the cost of flying the person to city A is aCost_i, and the cost of flying the person to city B is bCost_i.
Return the minimum cost to fly every person to a city such that exactly n people arrive in each city.
Visual Representation
Costs: [[10, 20], [30, 200], [400, 50], [30, 20]]
Profit of picking A over B (a - b):
1. 10 - 20 = -10
2. 30 - 200 = -170 (Huge saving if A)
3. 400 - 50 = +350 (Huge saving if B)
4. 30 - 20 = +10
Sorted diffs: -170, -10, +10, +350
Pick first 2 for A, last 2 for B.Examples
Fly person 1 and 2 to city A, and person 3 and 4 to city B.
Level I: Recursive Backtracking
Intuition
Try every possible way to assign people to City A and people to City B. This results in combinations.
Thought Process
solve(idx, countA, countB): Assign personidx.- Option 1: Assign to A (if
countA < n). - Option 2: Assign to B (if
countB < n). - Return minimum total cost from both paths.
Pattern: Brute Force / Combinations
Detailed Dry Run
[[10,20], [30,200]]
- A(10) then B(200) = 210
- B(20) then A(30) = 50 Min = 50.
Level II: Dynamic Programming
Intuition
This is a classic 2D DP problem. dp[i][j] represents the minimum cost for the first i+j people, with i people assigned to City A and j people assigned to City B.
Thought Process
dp[i][j]= min cost foriin A andjin B.- Transition:
dp[i][j] = min(dp[i-1][j] + costA, dp[i][j-1] + costB). - Base case:
dp[0][0] = 0.
Pattern: 2D Dynamic Programming
Detailed Dry Run
[[10,20], [30,200], [400,50], [30,20]] dp[1][0] = 10, dp[0][1] = 20 dp[1][1] = min(10+200, 20+30) = 50 dp[2][0] = 10+30 = 40 (N=2) ...
Level III: Optimal Greedy (Sorting by Relative Cost)
Intuition
Imagine we send everyone to City B first. Now we need to pick people to 'swap' to City A. To minimize total cost, we should pick the people for whom the cost reduction (or least increase) of moving to A is greatest. This is .
Thought Process
- Assume everyone goes to B initially (Total = ).
- The 'refund' we get by moving person to A instead of B is , or conversely, the 'extra cost' is .
- Sort all people by .
- Pick the first people (those with the most negative or smallest diffs) and send them to A.
Pattern: Greedy Difference Sorting
Detailed Dry Run
Costs: [[10,20], [30,200], [400,50], [30,20]] Diffs (A-B): [-10, -170, 350, 10] Sorted by diff: [-170, -10, 10, 350] People: [30,200], [10,20] -> Go to A. [30,20], [400,50] -> Go to B. Total: 30 + 10 + 20 + 50 = 110.
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.