diff --git a/cs/minimum-cost-to-hire-k-workers.cs b/cs/minimum-cost-to-hire-k-workers.cs new file mode 100644 index 0000000..d552fe1 --- /dev/null +++ b/cs/minimum-cost-to-hire-k-workers.cs @@ -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 { + 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(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(); + + 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; + } +}