-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
857 - Minimum Cost to Hire K Workers
- Loading branch information
Showing
1 changed file
with
43 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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; | ||
} | ||
}; |