- 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
- 44 lines of C++ from the credited upstream file 1606.cpp.
- The implementation visibly relies on sequence storage, ordered lookup, work queue.
- 4 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 vector<int> busiestServers(int k, vector<int>& arrival, vector<int>& load) {4 vector<int> ans;5 vector<int> times(k);6 set<int> idleServers;7 8 priority_queue<pair<int, int>, vector<pair<int, int>>, greater<>> minHeap;9 10 for (int i = 0; i < k; ++i)11 idleServers.insert(i);12 13 for (int i = 0; i < arrival.size(); ++i) {14 15 while (!minHeap.empty() && minHeap.top().first <= arrival[i]) {16 idleServers.insert(minHeap.top().second);17 minHeap.pop();18 }19 20 const int server = getNextAvailableServer(idleServers, i, k);21 if (server == -1)22 continue;23 ++times[server];24 minHeap.emplace(arrival[i] + load[i], server);25 idleServers.erase(server);26 }27 28 const int busiest = ranges::max(times);29 for (int i = 0; i < k; ++i)30 if (times[i] == busiest)31 ans.push_back(i);32 return ans;33 }34 35 private:36 int getNextAvailableServer(const set<int>& idleServers, int ithRequest,37 int k) {38 if (idleServers.empty())39 return -1;40 const auto it = idleServers.lower_bound(ithRequest % k);41 return it == idleServers.cend() ? *idleServers.begin() : *it;42 }43};44