LeetCode 826: Most Profit Assigning Work

Problem Description

Explanation:

To solve this problem, we need to maximize the total profit by assigning jobs to workers based on their abilities. We can sort the jobs based on their difficulty and profit in ascending order. Then, we can sort the workers based on their abilities in ascending order. We iterate through the sorted workers and for each worker, we find the maximum profit job they can complete within their ability. We keep track of the maximum profit achieved so far.

Algorithm:

  1. Sort the jobs based on difficulty and profit in ascending order.
  2. Sort the workers based on their abilities in ascending order.
  3. Initialize variables maxProfit to 0 and j to 0.
  4. Iterate through the sorted workers:
    • For each worker, find the maximum profit job they can complete within their ability by iterating through the jobs while j < n:
      • If the worker's ability is greater than or equal to the job difficulty, update the maximum profit and move to the next worker.
      • Increment j.
  5. Return the maxProfit.

Time Complexity: O(nlogn + mlogm) where n is the number of jobs and m is the number of workers. Space Complexity: O(1).

:

Solutions

class Solution {
    public int maxProfitAssignment(int[] difficulty, int[] profit, int[] worker) {
        int n = difficulty.length;
        int m = worker.length;
        int maxProfit = 0;
        
        int[][] jobs = new int[n][2];
        for (int i = 0; i < n; i++) {
            jobs[i][0] = difficulty[i];
            jobs[i][1] = profit[i];
        }
        Arrays.sort(jobs, (a, b) -> a[0] - b[0]);
        Arrays.sort(worker);
        
        int j = 0;
        int currProfit = 0;
        for (int ability : worker) {
            while (j < n && jobs[j][0] <= ability) {
                currProfit = Math.max(currProfit, jobs[j][1]);
                j++;
            }
            maxProfit += currProfit;
        }
        
        return maxProfit;
    }
}

Loading editor...