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)
1def maxProfitAssignment(difficulty, profit, worker):
2 jobs = sorted(zip(difficulty, profit))
3 worker.sort()
4
5 maxProfit = 0
6 best = 0
7 j = 0
8 n = len(jobs)
9
10 for ability in worker:
11 while j < n and ability >= jobs[j][0]:
12 best = max(best, jobs[j][1])
13 j += 1
14 maxProfit += best
15
16 return maxProfit
17
18print(maxProfitAssignment([2, 4, 6, 8, 10], [10, 20, 30, 40, 50], [4, 5, 6, 7]))
Python's sort and zip functions are used to prepare data. The main logic iterates over sorted workers and, using a pointer for jobs, it keeps track of the maximum profit any worker can achieve.
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)
The JavaScript implementation utilizes native array methods to manage job-processing to ensure max profit is always available for each worker evaluation. Complexity is minimized through precomputation.