1029. Two City Scheduling

68 阅读1分钟

image.png

方法

  • assume sending all people to A, total cost is sum
  • then, move some people, not to A, but to B,
  • the total cost in this case would be : sum +sumof(costB - costA)
  • then we need to find min of costB - costA, by sorting from low to high
  • then move first half to B, second half to A
class Solution {
    public int twoCitySchedCost(int[][] costs) {
        // sorting by costB - costA, from low to high
        Arrays.sort(costs, (a, b) -> (a[1] - a[0]) - (b[1] - b[0]));

        int len = costs.length;
        int res = 0;
        // first half, all to B
        for (int i = 0; i < len / 2; i++) {
            res += costs[i][1];
        }
        // second half, all to A
        for (int i = len/ 2; i < len; i++) {
            res += costs[i][0];
        }
        return res;
    }
}