2071. Maximum Number of Tasks You Can Assign.cpp #120
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Approach:
This problem combines binary search + greedy + deque simulation.
Binary Search:
We binary search on the number of tasks (mid) we can assign.
For each mid, we check if it's possible to assign the smallest mid tasks to the strongest mid workers.
Feasibility Check (canAssign):
Sort tasks and workers in ascending order.
Use a deque to track workers who can do a task with a pill (boosting their strength by strength).
Iterate over tasks (from hardest to easiest among selected mid tasks):
If a strong enough worker (without a pill) is available, assign directly.
Otherwise, push workers who can do the task with a pill into the deque.
Use a pill if needed and available; otherwise, fail.
If all tasks are assigned, return true.
Continue binary search until the maximum feasible number of tasks is found.
Intuition:
We want to maximize the number of tasks assigned by carefully distributing limited pills.
Binary search finds the upper limit, while the greedy check ensures pills are used optimally — only when weaker workers need them to complete harder tasks.
It’s like matching workers to tasks in the most efficient way possible under resource (pill) constraints.
Solution in Code (C++)
class Solution {
public:
int maxTaskAssign(vector& tasks, vector& workers, int pills, int strength) {
sort(tasks.begin(), tasks.end());
sort(workers.begin(), workers.end());
private:
bool canAssign(const vector& tasks, const vector& workers,
int pills, int strength, int taskCount) {
deque boosted;
int w = workers.size() - 1;
int freePills = pills;
};