Skip to content

Commit

Permalink
857 - Minimum Cost to Hire K Workers
Browse files Browse the repository at this point in the history
  • Loading branch information
f0rbit committed May 11, 2024
1 parent ef9cf6f commit ec67f76
Showing 1 changed file with 43 additions and 0 deletions.
43 changes: 43 additions & 0 deletions leetcode/hard/857-minimum_cost_to_hire_k_workers.cpp
@@ -0,0 +1,43 @@
class Solution {
public:
double mincostToHireWorkers(vector<int>& quality, vector<int>& wage, int k) {
int n = quality.size();
double totalCost = numeric_limits<double>::max();
double currentTotalQuality = 0;
// Store wage-to-quality ratio along with quality
vector<pair<double, int>> wageToQualityRatio;

// Calculate wage-to-quality ratio for each worker
for (int i = 0; i < n; i++) {
wageToQualityRatio.push_back(
{static_cast<double>(wage[i]) / quality[i], quality[i]});
}

// Sort workers based on their wage-to-quality ratio
sort(wageToQualityRatio.begin(), wageToQualityRatio.end());

// Use a priority queue to keep track of the highest quality workers
priority_queue<int> highestQualityWorkers;

// Iterate through workers
for (int i = 0; i < n; i++) {
highestQualityWorkers.push(wageToQualityRatio[i].second);
currentTotalQuality += wageToQualityRatio[i].second;

// If we have more than k workers,
// remove the one with the highest quality
if (highestQualityWorkers.size() > k) {
currentTotalQuality -= highestQualityWorkers.top();
highestQualityWorkers.pop();
}

// If we have exactly k workers,
// calculate the total cost and update if it's the minimum
if (highestQualityWorkers.size() == k) {
totalCost = min(totalCost, currentTotalQuality *
wageToQualityRatio[i].first);
}
}
return totalCost;
}
};

0 comments on commit ec67f76

Please sign in to comment.