../ Competitive Programming
-rw-r--r--aguang1.9 KiB2 min read

Leet Code Daily 2024-05-11 - Minimum Cost to Hire K Workers

Solution

Let's say HH is the set of hired workers and CiC_i is the cost of hired worker ii.

∣H∣=k\lvert H \rvert = k

We know all hired workers must be paid equally.

Given H,for each i∈H,CiQi=p\text{Given } H, \text{for each } i \in H, \frac{C_i}{Q_i} = p

And we also know the minimum wage WiW_i.

Ci=Qi×p≥WiC_i = Q_i \times p \geq W_i p≥WiQip \geq \frac{W_i}{Q_i}

The total cost would be:

∑i∈Hp×Qi\sum_{i \in H}{p \times Q_i}

Sort + Priority Queue

If we sort all workers by WiQi\frac{W_i}{Q_i}. Then, at any time, if worker ii is hired, all workers before ii can be hired with same p=WiQip = \frac{W_i}{Q_i}. And we only need to maintain top-k workers with smallest QiQ_i before to find current minimum cost.

Time Complexity

O(nlog⁡2n)O(n \log_2{n})

Code

c++
class Solution {
public:
    double mincostToHireWorkers(vector<int>& quality, vector<int>& wage,
                                int k) {
        vector<pair<int, int>> workers;
        for (int i = 0; i < quality.size(); i++) {
            workers.push_back(make_pair(quality[i], wage[i]));
        }
        sort(workers.begin(), workers.end(),
             [](const pair<int, int>& x, const pair<int, int>& y) {
                 return x.second * y.first < y.second * x.first;
             });
        double ans = 1E9;
        int total_quality = 0;
        priority_queue<int> hired_workers;
        for (const auto& w : workers) {
            total_quality += w.first;
            hired_workers.push(w.first);
            while (hired_workers.size() > k) {
                total_quality -= hired_workers.top();
                hired_workers.pop();
            }
            if (hired_workers.size() == k) {
                ans = min(ans, 1.0 * total_quality * w.second / w.first);
            }
        }
        return ans;
    }
};

COMMAND INTERFACE

↑ ↓ navigate · Enter execute · Esc exit · try “whoami”

Loading filesystem…

:help aguang.xyz

A personal website disguised as an operating system.

Ctrl / Cmd + K
Command palette + full-text search
Tab / Shift + Tab
Move between links and controls
Enter
Open a focused link or search result
↑ / ↓ in search
Navigate search results
In a directory filter
Enter/Done or ↓ focuses a result; Esc clears the filter
Esc
Clear a search or close a window