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)
1import java.util.Arrays;
2
3public class MaxProfitAssignment {
4 public static int maxProfitAssignment(int[] difficulty, int[] profit, int[] worker) {
5 int n = difficulty.length;
6 int[][] jobs = new int[n][2];
7 for (int i = 0; i < n; i++) {
8 jobs[i][0] = difficulty[i];
9 jobs[i][1] = profit[i];
10 }
11 Arrays.sort(jobs, (a, b) -> a[0] - b[0]);
12 Arrays.sort(worker);
13
14 int maxProfit = 0, best = 0, j = 0;
15 for (int ability : worker) {
16 while (j < n && ability >= jobs[j][0]) {
17 best = Math.max(best, jobs[j][1]);
18 j++;
19 }
20 maxProfit += best;
21 }
22 return maxProfit;
23 }
24
25 public static void main(String[] args) {
26 int[] difficulty = {2, 4, 6, 8, 10};
27 int[] profit = {10, 20, 30, 40, 50};
28 int[] worker = {4, 5, 6, 7};
29 System.out.println("Max Profit: " + maxProfitAssignment(difficulty, profit, worker));
30 }
31}
The Java solution employs two arrays to store jobs information and uses Arrays.sort() to sort both jobs and workers. It then iterates over the workers to find the job with maximum profit they can handle, updating this maximum in each step.
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.