857. Minimum Cost to Hire K Workers #192
-
Topics: There are We want to hire exactly
Given the integer Example 1:
Example 2:
Example 3:
Constraints:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to hire exactly
Key Insights:
Steps:
Let's implement this solution in PHP: 857. Minimum Cost to Hire K Workers <?php
/**
* @param Integer[] $quality
* @param Integer[] $wage
* @param Integer $k
* @return Float
*/
function mincostToHireWorkers(array $quality, array $wage, int $k): float
{
$n = count($quality);
$workers = array();
$ans = PHP_INT_MAX;
$qualitySum = 0;
// (wagePerQuality, quality) sorted by wagePerQuality
for ($i = 0; $i < $n; ++$i) {
$workers[$i] = array((double) $wage[$i] / $quality[$i], $quality[$i]);
}
// Sort by wagePerQuality ratio
usort($workers, function($a, $b) {
return $a[0] <=> $b[0];
});
// MaxHeap to keep track of largest quality workers
$maxHeap = new SplMaxHeap();
foreach ($workers as $worker) {
$wagePerQuality = $worker[0];
$q = $worker[1];
$qualitySum += $q;
$maxHeap->insert($q);
// Ensure the heap contains at most 'k' workers
if ($maxHeap->count() > $k) {
// Remove the worker with the largest quality
$qualitySum -= $maxHeap->extract();
}
// If we have exactly 'k' workers, calculate the cost
if ($maxHeap->count() == $k) {
// Total cost is (total quality of 'k' workers) * (current wagePerQuality)
$ans = min($ans, $qualitySum * $wagePerQuality);
}
}
return $ans;
}
// Example 1
$quality1 = [10, 20, 5];
$wage1 = [70, 50, 30];
$k1 = 2;
echo mincostToHireWorkers($quality1, $wage1, $k1) . "\n"; // Output: 105.00000
// Example 2
$quality2 = [3, 1, 10, 10, 1];
$wage2 = [4, 8, 2, 2, 7];
$k2 = 3;
echo mincostToHireWorkers($quality2, $wage2, $k2) . "\n"; // Output: 30.66667
// Example 3
$quality3 = [4, 4, 4, 5];
$wage3 = [13, 12, 13, 12];
$k3 = 2;
echo mincostToHireWorkers($quality3, $wage3, $k3) . "\n"; // Output: 26.00000
?> Explanation:
Example Walkthrough:Example 1:
Example 2:
Time Complexity:
This solution ensures that the least amount of money is paid while maintaining fairness and proportionality based on worker quality. |
Beta Was this translation helpful? Give feedback.
We need to hire exactly
k
workers while ensuring two conditions:Key Insights:
wage[i] / quality[i]
defines the minimum acceptable payment rate per unit of quality for workeri
. If we decide to hire a worker at this ratio, every other worker in the group must be paid according to this ratio.Steps:
wage[i] / quality[i]
ratio.