#826

Most Profit Assigning Work

Medium
ArrayTwo PointersBinary SearchGreedySortingSortingTwo Pointers
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log n + m log m)
Space
O(1)
O(n)
💡

Intuition

Time O(n log n + m log m)Space O(n)

In the optimal solution, we first pair jobs with their profits and sort them. Then, we sort the workers and use a two-pointer technique to efficiently find the maximum profit for each worker based on their ability.

⚙️

Algorithm

3 steps
  1. 1Step 1: Pair the difficulty and profit into a list of tuples and sort them based on difficulty.
  2. 2Step 2: Sort the workers array.
  3. 3Step 3: Use a pointer to track the maximum profit available for jobs that can be done by the current worker, and iterate through the workers to accumulate the total profit.
solution.py17 lines
1# Full working Python code
2
3def maxProfit(difficulty, profit, worker):
4    jobs = sorted(zip(difficulty, profit))
5    worker.sort()
6    total_profit = 0
7    max_profit = 0
8    j = 0
9    for w in worker:
10        while j < len(jobs) and jobs[j][0] <= w:
11            max_profit = max(max_profit, jobs[j][1])
12            j += 1
13        total_profit += max_profit
14    return total_profit
15
16# Example usage
17print(maxProfit([2,4,6,8,10], [10,20,30,40,50], [4,5,6,7]))

Complexity note: The time complexity is O(n log n + m log m) due to the sorting of jobs and workers. The space complexity is O(n) for storing the job pairs.

  • 1Workers can only take jobs they can handle, so sorting helps match them efficiently.
  • 2Using a two-pointer technique allows us to keep track of the maximum profit without redundant checks.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.