leetcode 1029. Two City Scheduling(两地调度)

A company is planning to interview 2n people. Given the array costs where costs[i] = [aCosti, bCosti], the cost of flying the ith person to city a is aCosti, and the cost of flying the ith person to city b is bCosti.

Return the minimum cost to fly every person to a city such that exactly n people arrive in each city.

Example 1:

Input: costs = [[10,20],[30,200],[400,50],[30,20]]
Output: 110
Explanation:
The first person goes to city A for a cost of 10.
The second person goes to city A for a cost of 30.
The third person goes to city B for a cost of 50.
The fourth person goes to city B for a cost of 20.

The total minimum cost is 10 + 30 + 50 + 20 = 110 to have half the people interviewing in each city.

给一个2n x 2的数组costs,其中costs[ i ] 为第 i 个人 到城市A 和 到城市B 的cost,即costs[ i ] = [costA, costB]。
要把这2n个人中的n个送到A, 另外n个送到B,问最小cost。

思路:
2n个人要对半分,n个去A,n个去B。
把 costA比costB小 的放在数组左边,costA比costB大 的放在数组右边。

涉及到了排序。
按什么排?按costA - costB排,也就是按costs[ i ][0] - costs[ i ][ 1 ]排序。

排好序后前半段加costA,后半段加costB。

    public int twoCitySchedCost(int[][] costs) {
        int n = costs.length / 2;
        int result = 0;
        int cnt = 0;
        
        Arrays.sort(costs, (a, b) -> (a[0] - a[1] - b[0] + b[1]));
        
        for(int[] cost : costs) {
            if(cnt < n) {
                result += cost[0];
            } else {
                result += cost[1];
            }
            cnt ++;
        }
        
        return result;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蓝羽飞鸟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值