LOADING...

ZS_2462_雇佣 K 位工人的总代价

思路

两个小顶堆借助左右两个指针将数组元素遍历,不断比较两个小顶堆的堆顶元素,累加两者更小的价格(相等优先加左边的);

为保证candidates满足条件,先进行candidates次;

最后得出总价格;

优先队列

优先队列的本质是数据结构中的树,Java中的Queue接口用PriorityQueue实现类实现,可创建默认的小顶堆。

具体实现:

![image-20221111164214464](ZS_2462_雇佣 K 位工人的总代价.assets/image-20221111164214464.png)

代码

    public static long totalCost(int[] costs, int k, int candidates) {
        Queue<Integer> leftQueue = new PriorityQueue<>();
        Queue<Integer> rightQueue = new PriorityQueue<>();
        int len = costs.length;
        long total = 0L;
        int leftP = 0, rightP = len - 1;
        for (int i = 0; i < candidates; i++) {
            if (leftP <= rightP)
                leftQueue.offer(costs[leftP++]);
            if (leftP <= rightP)
                rightQueue.offer(costs[rightP--]);
        }
        while (k != 0) {
            int minL = leftQueue.peek() == null ? Integer.MAX_VALUE : leftQueue.peek();
            int minR = rightQueue.peek() == null ? Integer.MAX_VALUE : rightQueue.peek();
            if (minL <= minR) {
                leftQueue.poll();
                total += minL;
                if (leftP <= rightP)
                    leftQueue.offer(costs[leftP++]);
            } else {
                rightQueue.poll();
                total += minR;
                if (leftP <= rightP)
                    rightQueue.offer(costs[rightP--]);
            }
            k--;
        }
        return total;
    }
posted @ 2022-11-11 17:16  Pilo-pillow  阅读(32)  评论(0)    收藏  举报