You are given a 0-indexed integer array costs where costs[i] is the cost of hiring the ith worker.
You are also given two integers k and candidates. We want to hire exactly k workers according to the following rules:
k sessions and hire exactly one worker in each session.candidates workers or the last candidates workers. Break the tie by the smallest index.costs = [3,2,7,7,1,2] and candidates = 2, then in the first hiring session, we will choose the 4th worker because they have the lowest cost [3,2,7,7,1,2].1st worker because they have the same lowest cost as 4th worker but they have the smallest index [3,2,7,7,2]. Please note that the indexing may be changed in the process.Return the total cost to hire exactly k workers.
비용 배열 costs가 주어집니다. 이 배열은 0번부터 인덱싱되며 costs[i]는 i번째 근로자를 고용하는데 필요한 비용입니다.
또한 정수 k와 candidates가 주어집니다. 다음 규칙에 따라 정확히 k명의 근로자를 고용하고자 합니다:
k 세션을 진행하며 각 세션에서 정확히 한 명의 근로자를 고용합니다.candidates명의 근로자들 또는 마지막 candidates명의 근로자들 중에서 가장 비용이 낮은 근로자를 선택합니다. 비용이 같을 경우 인덱스가 가장 작은 근로자를 선택합니다.costs = [3,2,7,7,1,2]이고 candidates = 2라면 첫 번째 고용 세션에서는 4번째 근로자를 선택하게 됩니다. 그들은 가장 낮은 비용 [3,2,7,7,1,2]을 가지고 있습니다.정확히 k명의 근로자를 고용하기 위한 총 비용을 반환하세요.
입력: costs = [17,12,10,2,7,2,11,20,8], k = 3, candidates = 4
출력: 11
설명: 총 3명의 근로자를 고용합니다. 초기 총 비용은 0입니다.
입력: costs = [1,2,4,1], k = 3, candidates = 3
출력: 4
설명: 총 3명의 근로자를 고용합니다. 초기 총 비용은 0입니다.
1 <= costs.length <= 1051 <= costs[i] <= 1051 <= k, candidates <= costs.lengthclass Solution {
public long totalCost(int[] costs, int k, int candidates) {
// 두 큐를 초기화합니다. 각 큐는 배열의 양 끝에서 시작하여 비용을 관리합니다.
PriorityQueue<Integer> leftQueue = new PriorityQueue<>();
PriorityQueue<Integer> rightQueue = new PriorityQueue<>();
// 양쪽 끝에서 시작하는 포인터입니다.
int leftIndex = 0;
int rightIndex = costs.length - 1;
// 최종 비용을 저장할 변수입니다.
long totalCost = 0;
// k명의 근로자를 선택합니다.
while (k-- > 0) {
// leftQueue에 candidates 수만큼 원소를 추가합니다.
while (leftQueue.size() < candidates && leftIndex <= rightIndex) {
leftQueue.offer(costs[leftIndex++]);
}
// rightQueue에 candidates 수만큼 원소를 추가합니다.
while (rightQueue.size() < candidates && leftIndex <= rightIndex) {
rightQueue.offer(costs[rightIndex--]);
}
// 각 큐에서 최소값을 비교합니다.
int minLeft = leftQueue.isEmpty() ? Integer.MAX_VALUE : leftQueue.peek();
int minRight = rightQueue.isEmpty() ? Integer.MAX_VALUE : rightQueue.peek();
// 더 작은 비용의 근로자를 선택하고 해당 큐에서 제거합니다.
if (minLeft <= minRight) {
totalCost += minLeft;
leftQueue.poll();
} else {
totalCost += minRight;
rightQueue.poll();
}
}
return totalCost;
}
}