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)
1using System;
2using System.Linq;
3
4public class Solution {
5 public int MaxProfitAssignment(int[] difficulty, int[] profit, int[] worker) {
6 var jobs = difficulty.Zip(profit, (d, p) => new { Difficulty = d, Profit = p })
7 .OrderBy(j => j.Difficulty)
8 .ToArray();
9 Array.Sort(worker);
10
11 int maxProfit = 0, best = 0, j = 0;
12 foreach (int ability in worker) {
13 while (j < jobs.Length && ability >= jobs[j].Difficulty) {
14 best = Math.Max(best, jobs[j].Profit);
15 j++;
16 }
17 maxProfit += best;
18 }
19 return maxProfit;
20 }
21
22 public static void Main() {
23 var solution = new Solution();
24 Console.WriteLine(solution.MaxProfitAssignment(new int[] {2, 4, 6, 8, 10}, new int[] {10, 20, 30, 40, 50}, new int[] {4, 5, 6, 7}));
25 }
26}
This C# solution uses the LINQ Zip and OrderBy methods to sort combined job data, then it processes workers through a sorted array to find the best available profit for each.
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 Java version efficiently updates the max profit in the jobs array during job processing, helping fast profit calculation for each worker by leveraging precomputed data.