Re: [闲聊] 每日LeetCode

楼主: Rushia (みけねこ的鼻屎)   2023-06-27 09:17:28
https://leetcode.com/problems/total-cost-to-hire-k-workers/description/
2462. Total Cost to Hire K Workers
给你一个阵列costs,costs[i] 表示第 i 个应征者的期望薪资,我们要开一个会议
每次从最左边和最右的应征者开始挑选 candidates 个人,并从中雇用最便宜的应征
者(成本相同的话靠左的人优先),剩下的人进入下一轮会议,公司需要挑选出 k 个人,求出雇用的最小成本。
Example 1:
Input: costs = [17,12,10,2,7,2,11,20,8], k = 3, candidates = 4
Output: 11
Explanation: We hire 3 workers in total. The total cost is initially 0.
- In the first hiring round we choose the worker from
[17,12,10,2,7,2,11,20,8]. The lowest cost is 2, and we break the tie by the
smallest index, which is 3. The total cost = 0 + 2 = 2.
- In the second hiring round we choose the worker from
[17,12,10,7,2,11,20,8]. The lowest cost is 2 (index 4). The total cost = 2 +
2 = 4.
- In the third hiring round we choose the worker from [17,12,10,7,11,20,8].
The lowest cost is 7 (index 3). The total cost = 4 + 7 = 11. Notice that the
worker with index 3 was common in the first and last four workers.
The total hiring cost is 11.
思路:
1.照题目需求,每次都从最左边和最右边挑选 candidates 个人并放进 Min Heap 里
按 costs 排序,相同就比较索引,这样每次拿出来的就会是最优解,如果取了左边的
人那下次就要先从左边补人,右边反之。
(原始的解法太丑了我就不贴了)
2.上面是比较直观的解,还可以做一些优化,开头可以直接判断 candidates 是否可以
直接包含全部 costs,这样只要直接排序后取 k 个就是最佳解,不必一直维护heap。
3.可以用两个 Heap 来保存左半边和右半边,左半边的 Heap 优先取出,可以免除一些
繁琐的判断。
Java Code:

Links booklink

Contact Us: admin [ a t ] ucptt.com