- Identify the ordered answer range or sorted search domain.
- Write a predicate whose truth changes only once.
- Move the appropriate boundary after each midpoint check and return the final feasible position.
Code notes
- 57 lines of C++ from the credited upstream file 2071.cpp.
- The implementation visibly relies on sequence storage, ordered lookup.
- 3 loop blocks detected.
Complexity
Multiply the logarithmic number of midpoint checks by the cost of one predicate evaluation.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public:3 int maxTaskAssign(vector<int>& tasks, vector<int>& workers, int pills,4 int strength) {5 int ans = 0;6 int l = 0;7 int r = min(tasks.size(), workers.size());8 9 ranges::sort(tasks);10 ranges::sort(workers);11 12 13 auto canComplete = [&](int k, int pillsLeft) {14 15 map<int, int> sortedWorkers;16 for (int i = workers.size() - k; i < workers.size(); ++i)17 ++sortedWorkers[workers[i]];18 19 20 for (int i = k - 1; i >= 0; --i) {21 22 auto it = sortedWorkers.lower_bound(tasks[i]);23 if (it != sortedWorkers.end()) {24 if (--(it->second) == 0)25 sortedWorkers.erase(it);26 } else if (pillsLeft > 0) {27 28 it = sortedWorkers.lower_bound(tasks[i] - strength);29 if (it != sortedWorkers.end()) {30 if (--(it->second) == 0)31 sortedWorkers.erase(it);32 --pillsLeft;33 } else {34 return false;35 }36 } else {37 return false;38 }39 }40 41 return true;42 };43 44 while (l <= r) {45 const int m = (l + r) / 2;46 if (canComplete(m, pills)) {47 ans = m;48 l = m + 1;49 } else {50 r = m - 1;51 }52 }53 54 return ans;55 }56};57