Sponsored
Sponsored
In this approach, we sort both jobs by difficulty and workers by their ability. We then iterate over each worker and find the highest profit job they can perform using a greedy approach.
First, we pair each job's difficulty with its profit and then sort these pairs by difficulty. We also sort the worker array. Next, for each worker, we iterate through the sorted job list and keep track of the maximum profit the worker can obtain, given that their ability must be greater than or equal to the job's difficulty. This ensures that each worker is assigned the most profitable job they can perform, thus maximizing the total profit.
Time Complexity: O(n log n + m log m)
Space Complexity: O(n)
1function maxProfitAssignment(difficulty, profit, worker) {
2 const jobs = difficulty.map((d, i) => [d, profit[i]]);
3 jobs.sort((a, b) => a[0] - b[0]);
4 worker.sort((a, b) => a - b);
5
6 let maxProfit = 0, best = 0, j = 0;
7 for (let ability of worker) {
8 while (j < jobs.length && ability >= jobs[j][0]) {
9 best = Math.max(best, jobs[j][1]);
10 j++;
11 }
12 maxProfit += best;
13 }
14 return maxProfit;
15}
16
17console.log(maxProfitAssignment([2, 4, 6, 8, 10], [10, 20, 30, 40, 50], [4, 5, 6, 7]));
The JavaScript solution utilizes sorting to align jobs by difficulty and workers by capacity. It then iterates over each worker and assigns them the most profitable job they are qualified for.
This approach improves efficiency by preparing the job list in advance for profit maximization, and processes each worker in one pass. The basic idea is to preprocess the jobs to track the maximum profit obtainable up to each difficulty level. We create a running maximum profit and apply this to each worker based on their ability directly.
First, jobs are paired and sorted by difficulty; then, as we iterate through them, we constantly update the maximum profit obtainable up to each job's difficulty. When assessing workers, we simply apply their ability to this precomputed list to find the applicable maximum profit, ensuring minimal lookups and passing through the sorted jobs just once.
Time Complexity: O(n log n + m log m)
Space Complexity: O(n)
This Python implementation precomputes the maximum possible profit up to each job using sorted resources. Workers access these precomputed profits for optimal matching in a streamlined search.