826. Most Profit Assigning Work #186
-
Topics: You have
Every worker can be assigned at most one job, but one job can be completed multiple times.
Return the maximum profit we can achieve after assigning the workers to the jobs. Example 1:
Example 2:
Constraints:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to assign workers to jobs in such a way that each worker can only do jobs they are capable of based on their ability (which means their ability must be greater than or equal to the job's difficulty). The goal is to maximize the total profit, and one job can be completed multiple times by different workers. Plan:
Steps:
Let's implement this solution in PHP: 826. Most Profit Assigning Work <?php
/**
* @param Integer[] $difficulty
* @param Integer[] $profit
* @param Integer[] $worker
* @return Integer
*/
function maxProfitAssignment($difficulty, $profit, $worker) {
// Combine difficulty and profit into a list of jobs
$jobs = [];
for ($i = 0; $i < count($difficulty); $i++) {
$jobs[] = [$difficulty[$i], $profit[$i]];
}
// Sort jobs by difficulty (and by profit in case of tie in difficulty)
usort($jobs, function($a, $b) {
if ($a[0] == $b[0]) {
return $b[1] - $a[1]; // sort by profit if difficulties are the same
}
return $a[0] - $b[0]; // sort by difficulty
});
// Sort the workers by their ability
sort($worker);
$maxProfit = 0;
$totalProfit = 0;
$i = 0; // job index
// Iterate over each worker
foreach ($worker as $ability) {
// Assign the best job to the current worker
while ($i < count($jobs) && $jobs[$i][0] <= $ability) {
$maxProfit = max($maxProfit, $jobs[$i][1]);
$i++;
}
// Add the best profit the worker can achieve
$totalProfit += $maxProfit;
}
return $totalProfit;
}
// Test cases
$difficulty = [2, 4, 6, 8, 10];
$profit = [10, 20, 30, 40, 50];
$worker = [4, 5, 6, 7];
echo maxProfitAssignment($difficulty, $profit, $worker); // Output: 100
$difficulty = [85, 47, 57];
$profit = [24, 66, 99];
$worker = [40, 25, 25];
echo maxProfitAssignment($difficulty, $profit, $worker); // Output: 0
?> Explanation:
Time Complexity:
Space Complexity:
|
Beta Was this translation helpful? Give feedback.
We need to assign workers to jobs in such a way that each worker can only do jobs they are capable of based on their ability (which means their ability must be greater than or equal to the job's difficulty). The goal is to maximize the total profit, and one job can be completed multiple times by different workers.
Plan:
Steps: