Imagine you're a project manager with n tasks to complete and m workers available. Each task has a specific strength requirement, and each worker has their own strength level. A worker can only handle a task if their strength is greater than or equal to the task's requirement.
Here's the twist: you have pills magical energy boosters that can increase any worker's strength by strength points! Each worker can receive at most one pill, and you need to decide strategically who gets them.
Goal: Determine the maximum number of tasks you can complete by optimally assigning workers to tasks and distributing the magical pills.
Input: Two arrays tasks[] and workers[] representing strength requirements and worker strengths, plus integers pills and strength.
Output: Maximum number of tasks that can be completed.
💡 Note:We can complete all 3 tasks: assign worker with strength 3 to task requiring 3, worker with strength 1 to task requiring 1, and give a pill to worker with strength 0 (becomes 3) to handle task requiring 2.
💡 Note:We have 3 workers each with 0 strength, but only 1 pill that adds 5 strength. So only one worker can be enhanced to strength 5, allowing completion of only 1 task.
The optimal approach uses binary search on the answer combined with a greedy validation strategy. We search for the maximum number of tasks we can complete (0 to min(n,m)), and for each candidate, we validate using a greedy approach: sort both arrays, then try to assign the easiest k tasks to workers, always preferring the strongest available worker and using pills strategically only when normal assignment fails. Time complexity: O(n log n log n).
Common Approaches
✓
Binary Search + Greedy (Optimal)
⏱️ Time: O(n log n log n)
Space: O(n)
This optimal approach uses binary search on the number of tasks we can complete. For each candidate answer, we validate if it's achievable using a greedy strategy: sort tasks and workers, then try to assign the easiest remaining tasks to the strongest available workers, using pills strategically only when necessary.
Brute Force (Try All Combinations)
⏱️ Time: O(2^m × n!)
Space: O(m + n)
This approach tries every possible combination of giving pills to workers, then for each combination, attempts to find the maximum matching between enhanced workers and tasks. It uses recursive backtracking to explore all possibilities.