|
| 1 | +classSolution { |
| 2 | +publiclongtotalCost(int[]costs,intk,intcandidates) { |
| 3 | +PriorityQueue<Integer>headWorkers =newPriorityQueue<>(); |
| 4 | +PriorityQueue<Integer>tailWorkers =newPriorityQueue<>(); |
| 5 | +for (inti =0;i <candidates;i++) { |
| 6 | +headWorkers.add(costs[i]); |
| 7 | + } |
| 8 | +for (inti =Math.max(candidates,costs.length -candidates);i <costs.length;i++) { |
| 9 | +tailWorkers.add(costs[i]); |
| 10 | + } |
| 11 | +intheadIdx =candidates; |
| 12 | +inttailIdx =costs.length -candidates -1; |
| 13 | +longresult =0; |
| 14 | +for (inti =0;i <k;i++) { |
| 15 | +if (tailWorkers.isEmpty() || (!headWorkers.isEmpty() &&headWorkers.peek() <=tailWorkers.peek())) { |
| 16 | +result +=headWorkers.poll(); |
| 17 | +if (headIdx <=tailIdx) { |
| 18 | +headWorkers.add(costs[headIdx++]); |
| 19 | + } |
| 20 | + }else { |
| 21 | +result +=tailWorkers.poll(); |
| 22 | +if (headIdx <=tailIdx) { |
| 23 | +tailWorkers.add(costs[tailIdx--]); |
| 24 | + } |
| 25 | + } |
| 26 | + } |
| 27 | +returnresult; |
| 28 | + } |
| 29 | +} |