Greedy Algorithms8 sections · 316 units
Open in Course

Two City - Implementation

The code

Here is the solution:

function twoCitySchedCost(costs)
 sort costs by (cost[0] - cost[1]) ascending
 total := 0
 n := length / 2
 for i from 0 to n - 1
 total := total + costs[i][0]
 for i from n to length - 1
 total := total + costs[i][1]
 return total

Time: O(nlogn)O(n \log n). Space: O(1)O(1).

People with the smallest costAcostBcost_A - cost_B should go to A. That means A is relatively cheaper for them.