Problem
You have n jobs and m workers. You are given three arrays: difficulty, profit, and worker where:
difficulty[i]andprofit[i]are the difficulty and the profit of theithjob, andworker[j]is the ability ofjthworker (i.e., thejthworker can only complete a job with difficulty at mostworker[j]).
Every worker can be assigned at most one job, but one job can be completed multiple times.
- For example, if three workers attempt the same job that pays
$1, then the total profit will be$3. If a worker cannot complete any job, their profit is$0.
Return the maximum profit we can achieve after assigning the workers to the jobs.
Examples
Example 1:
| |
Example 2:
| |
Solution
Method 1 - Sorting
Lets take the examples: difficulty = [68,35,52,47,86], profit = [67,17,1,81,3], worker = [92,10,85,84,82]
- First thing we do is sort the
{difficulty[i], profit[i]}pair based ondifficulty, because we are given theworkerarray as the job difficulty handling ability of worker. Then we get following arrays:difficulty = [35,47,52,68,86], profit = [17,81,1,67,3] - Now, if a worker can do a job at difficulty level A then they can do all the jobs with difficulty less than or equal to A. For eg.
A = 52, the worker can handle difficulty[35, 47, 52]and profits[17, 81, 1]and we get the a maximum profit as 81. - So, we update the profit values with the maximum profit from previous ones.
profit[i] = max(profit[i], profit[i - 1])⇨ We loop from left to right tprofit = [17, 81, 81, 81, 81]
- Now we can apply binary search(upper bound) for every worker and individually assign jobs finally get the max profit.
difficulty = [35,47,52,68,86], profit = [17, 81, 81, 81, 81]worker = [92,10,85,84,82]- Defile
maxProfit = 0 i = 0, worker[i] = 92⇨ we try to find the highest difficulty less than or equal to 92, which return 86 and profit associated to it is 81.maxProfit += 81 = 0i = 1, worker = 10⇨ We couldn’t find any job that can be done by worker with ability 10.i = 2, worker[i] = 85⇨ we try to find the highest difficulty less than or equal to 85, which return 68 and profit associated to it is 81.maxProfit += 81 = 162i = 3, worker[i] = 84⇨ we try to find the highest difficulty less than or equal to 84, which return 68 and profit associated to it is 81.maxProfit += 81 = 243i = 4, worker[i] = 82⇨ we try to find the highest difficulty less than or equal to 82, which return 68 and profit associated to it is 81.maxProfit += 81 = 324
- So, we return maxProfit of
324
Here is the video explanation of the same:
Code
| |
Complexity
- ⏰ Time complexity:
O((n + m) log n)wherenis number of jobs, andmis number of workers. The reason is we sort the jobs array, which takesO(n log n), then we update profit array, which takesO(n)time, finally we apply binary search formworkers injobs.difficultyarray, which takesm log ntime. So, we sum upO(n log n) + O(n) + O(m log n)=O( (n + m) log n) - 🧺 Space complexity:
O(n)as we are creating new job array to store difficulty and profit pair.