Problem Description
Given two arrays, tasks and workers, where each task has a minimum strength requirement and each worker has a current strength, determine the maximum number of tasks that can be completed. Each worker can perform at most one task if their strength is greater than or equal to the task's requirement. Additionally, you have a limited number of magical pills that can boost a worker's strength by a fixed value (each worker may receive at most one pill). The objective is to maximize the number of completed tasks by smartly assigning workers and pills.
Key Insights
- Sort both tasks and workers to facilitate greedy matching.
- Use binary search to determine the maximum number of tasks that can be assigned.
- Develop a feasibility function that checks if x tasks can be fulfilled by pairing the x hardest tasks with x appropriate workers.
- Greedily assign tasks: use a worker if they meet the requirement without a pill; otherwise, use a pill if available and effective.
- The binary search narrows down the best achievable number of completed tasks.
Space and Time Complexity
Time Complexity: O(n log n + m log m + (n+m) log(min(n, m)))
Space Complexity: O(n + m)
Solution
The solution begins by sorting both the tasks and workers arrays. Then, we use binary search to decide the maximum number of tasks that can be assigned (x). For each candidate x, a feasibility check is performed where we try to match the x hardest tasks (the last x elements in tasks after sorting) with the x weakest workers that can be assigned (a subarray from workers). For each task, if the worker’s strength is enough, we assign the task directly; if not but a pill can boost the worker to the necessary level, we apply the pill (if available). If neither condition is met for any task, then x is not achievable. Adjusting the binary search bounds based on feasibility will find the maximum possible task assignment.