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.
1using System;
2using System.Collections.Generic;
3
4public class Solution {
5 public int TwoCitySchedCost(int[][] costs) {
6 Array.Sort(costs, (a, b) => (a[0] - a[1]) - (b[0] - b[1]));
7 int totalCost = 0;
8 int n = costs.Length / 2;
9 for (int i = 0; i < n; i++) {
10 totalCost += costs[i][0] + costs[i + n][1];
11 }
12 return totalCost;
13 }
14}
This C# solution uses Array.Sort()
with a custom comparator to sort by difference in assessed costs, then aggregates the total minimal cost for sending n individuals to both cities in balance.