Sponsored
Sponsored
This approach relies on sorting the people by the difference between the cost of flying them to city A and city B. By doing so, we can initially assume that flying every person to city A is optimal, and then we adjust half of the people to go to city B based on minimal added cost.
The time complexity of this solution is O(n log n) due to the sorting step, and the space complexity is O(1) since we are sorting in place.
1var twoCitySchedCost = function(costs) {
2 costs.sort((a, b) => (a[0] - a[1]) - (b[0] - b[1]));
3 let totalCost = 0;
4 for (let i = 0; i < costs.length / 2; i++) {
5 totalCost += costs[i][0] + costs[i + costs.length / 2][1];
6 }
7 return totalCost;
8};
In JavaScript, the solution involves first sorting the persons by the saving incurred when sending them to city A instead of city B and computing the necessary costs for the optimal distribution between the cities.