Maximize Profit from Task Assignment - Problem

You are given an integer array workers, where workers[i] represents the skill level of the i-th worker. You are also given a 2D integer array tasks, where:

  • tasks[i][0] represents the skill requirement needed to complete the task
  • tasks[i][1] represents the profit earned from completing the task

Each worker can complete at most one task, and they can only take a task if their skill level is equal to the task's skill requirement. An additional worker joins today who can take up any task, regardless of the skill requirement.

Return the maximum total profit that can be earned by optimally assigning the tasks to the workers.

Input & Output

Example 1 — Basic Assignment
$ Input: workers = [3,1,2], tasks = [[1,7],[2,4],[3,5]]
Output: 16
💡 Note: Worker with skill 1 takes task [1,7] for profit 7, worker with skill 2 takes task [2,4] for profit 4, worker with skill 3 takes task [3,5] for profit 5. Total profit = 7 + 4 + 5 = 16
Example 2 — Super Worker Needed
$ Input: workers = [1,1], tasks = [[1,5],[2,6],[1,3]]
Output: 14
💡 Note: Two workers with skill 1 can take tasks [1,5] and [1,3] for profit 5+3=8. Super worker takes remaining task [2,6] for profit 6. Total = 8 + 6 = 14
Example 3 — More Tasks Than Workers
$ Input: workers = [2], tasks = [[1,8],[2,7],[3,6]]
Output: 15
💡 Note: Regular worker with skill 2 takes task [2,7] for profit 7. Super worker takes highest remaining task [1,8] for profit 8. Total = 7 + 8 = 15

Constraints

  • 1 ≤ workers.length ≤ 105
  • 1 ≤ tasks.length ≤ 105
  • 1 ≤ workers[i], tasks[i][0] ≤ 105
  • 1 ≤ tasks[i][1] ≤ 108

Visualization

Tap to expand
Maximize Profit from Task Assignment INPUT Workers (Skill Levels) 3 1 2 Tasks [Skill, Profit] Skill Profit 1 7 2 4 3 5 + SPECIAL WORKER Can do ANY task ALGORITHM STEPS 1 Sort Tasks by Profit [1,7] [3,5] [2,4] 2 Count Worker Skills skill 1:1, skill 2:1, skill 3:1 3 Greedy Assignment High profit first Task[1,7]: Worker skill=1 OK +7 Task[3,5]: Worker skill=3 OK +5 Task[2,4]: Worker skill=2 OK +4 Special worker: No task left 4 Sum All Profits 7 + 5 + 4 = 16 FINAL RESULT Optimal Assignment W1 (s=1) --> T[1,7] +7 W2 (s=2) --> T[2,4] +4 W3 (s=3) --> T[3,5] +5 Special --> None +0 Maximum Profit 16 OK - All workers assigned optimally! Key Insight: Greedy approach works because sorting tasks by profit (descending) ensures we always pick the most valuable task first. The special worker should only be used when regular workers cannot take a high-profit task, but in this case, all tasks are covered by matching skill workers, maximizing total profit to 16. TutorialsPoint - Maximize Profit from Task Assignment | Greedy - Sort by Profit
Asked in
Google 45 Amazon 38 Microsoft 32 Facebook 28
34.2K Views
Medium Frequency
~25 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen