cs: add «857. Minimum Cost to Hire K Workers»
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
parent
3bc4d1bb81
commit
4a3c33cda8
1 changed files with 43 additions and 0 deletions
43
cs/minimum-cost-to-hire-k-workers.cs
Normal file
43
cs/minimum-cost-to-hire-k-workers.cs
Normal file
|
@ -0,0 +1,43 @@
|
|||
using System.Collections.Generic;
|
||||
|
||||
public class Solution {
|
||||
private struct Worker(int quality, int wage) {
|
||||
public int Quality => quality;
|
||||
public int Wage => wage;
|
||||
public double Ratio => (double)Wage / Quality;
|
||||
}
|
||||
private class WorkerComparator : IComparer<Worker> {
|
||||
public int Compare(Worker lhs, Worker rhs) {
|
||||
var l = lhs.Wage * rhs.Quality;
|
||||
var r = rhs.Wage * lhs.Quality;
|
||||
return l.CompareTo(r);
|
||||
}
|
||||
}
|
||||
|
||||
public double MincostToHireWorkers(int[] quality, int[] wage, int k) {
|
||||
var workers = new List<Worker>(quality.Length);
|
||||
for (var i = 0; i < quality.Length; ++i) {
|
||||
workers.Add(new Worker(quality[i], wage[i]));
|
||||
}
|
||||
workers.Sort(new WorkerComparator());
|
||||
|
||||
double cost = double.MaxValue;
|
||||
int currentQuality = 0;
|
||||
var heap = new PriorityQueue<int, int>();
|
||||
|
||||
foreach (var worker in workers) {
|
||||
currentQuality += worker.Quality;
|
||||
heap.Enqueue(worker.Quality, -worker.Quality);
|
||||
|
||||
if (heap.Count > k) {
|
||||
currentQuality -= heap.Dequeue();
|
||||
}
|
||||
|
||||
if (heap.Count == k) {
|
||||
cost = Math.Min(cost, currentQuality * worker.Ratio);
|
||||
}
|
||||
}
|
||||
|
||||
return cost;
|
||||
}
|
||||
}
|
Loading…
Reference in a new issue