|
| 1 | +/** |
| 2 | + * 2462. Total Cost to Hire K Workers |
| 3 | + * https://leetcode.com/problems/total-cost-to-hire-k-workers/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * You are given a 0-indexed integer array costs where costs[i] is the cost of hiring |
| 7 | + * the ith worker. |
| 8 | + * |
| 9 | + * You are also given two integers k and candidates. We want to hire exactly k workers |
| 10 | + * according to the following rules: |
| 11 | + * - You will run k sessions and hire exactly one worker in each session. |
| 12 | + * - In each hiring session, choose the worker with the lowest cost from either the first |
| 13 | + * candidates workers or the last candidates workers. Break the tie by the smallest index. |
| 14 | + * - For example, if costs = [3,2,7,7,1,2] and candidates = 2, then in the first hiring |
| 15 | + * session, we will choose the 4th worker because they have the lowest cost [3,2,7,7,1,2]. |
| 16 | + * - In the second hiring session, we will choose 1st worker because they have the same |
| 17 | + * lowest cost as 4th worker but they have the smallest index [3,2,7,7,2]. Please note |
| 18 | + * that the indexing may be changed in the process. |
| 19 | + * - If there are fewer than candidates workers remaining, choose the worker with the lowest |
| 20 | + * cost among them. Break the tie by the smallest index. |
| 21 | + * - A worker can only be chosen once. |
| 22 | + * |
| 23 | + * Return the total cost to hire exactly k workers. |
| 24 | + */ |
| 25 | + |
| 26 | +/** |
| 27 | + * @param {number[]} costs |
| 28 | + * @param {number} k |
| 29 | + * @param {number} candidates |
| 30 | + * @return {number} |
| 31 | + */ |
| 32 | +var totalCost = function(costs, k, candidates) { |
| 33 | + const queue = new PriorityQueue({ compare: (a, b) => { |
| 34 | + return a[0] === b[0] ? a[1] - b[1] : a[0] - b[0]; |
| 35 | + }}); |
| 36 | + |
| 37 | + costs.forEach((cost, index) => { |
| 38 | + if (index < candidates || index >= costs.length - candidates) { |
| 39 | + queue.enqueue([cost, index]); |
| 40 | + } |
| 41 | + }); |
| 42 | + |
| 43 | + let result = 0; |
| 44 | + for (let i = 0, count = candidates, diff = costs.length - candidates - 1; i < k; i++) { |
| 45 | + const worker = queue.dequeue(); |
| 46 | + result += worker[0]; |
| 47 | + |
| 48 | + if (count <= diff) { |
| 49 | + let status = null; |
| 50 | + if (worker[1] < count) { |
| 51 | + status = [costs[count], count]; |
| 52 | + count++; |
| 53 | + } else { |
| 54 | + status = [costs[diff], diff]; |
| 55 | + diff--; |
| 56 | + } |
| 57 | + queue.enqueue(status); |
| 58 | + } |
| 59 | + } |
| 60 | + |
| 61 | + return result; |
| 62 | +}; |
0 commit comments