- 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
- 75 lines of C++ from the credited upstream file 2819.cpp.
- The implementation visibly relies on sequence storage.
- 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 vector<long long> minimumRelativeLosses(vector<int>& prices,4 vector<vector<int>>& queries) {5 const int n = prices.size();6 vector<long long> ans;7 vector<long long> prefix{0};8 9 ranges::sort(prices);10 11 for (const int price : prices)12 prefix.push_back(prefix.back() + price);13 14 for (const vector<int>& query : queries) {15 const int k = query[0];16 const int m = query[1];17 const int countFront = getCountFront(k, m, prices);18 const int countBack = m - countFront;19 ans.push_back(getRelativeLoss(countFront, countBack, k, prefix));20 }21 22 return ans;23 }24 25 private:26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 int getCountFront(int k, int m, const vector<int>& prices) {45 const int n = prices.size();46 const int countNoGreaterThanK =47 ranges::upper_bound(prices, k) - prices.begin();48 int l = 0;49 int r = min(countNoGreaterThanK, m);50 51 while (l < r) {52 const int mid = (l + r) / 2;53 const int right = m - mid;54 55 if (prices[mid] < 2L * k - prices[n - right])56 l = mid + 1;57 else58 r = mid;59 }60 61 return l;62 }63 64 65 66 long getRelativeLoss(int countFront, int countBack, int k,67 const vector<long long>& prefix) {68 const long lossFront = prefix[countFront];69 const long lossBack =70 2L * k * countBack -71 (prefix.back() - prefix[prefix.size() - 1 - countBack]);72 return lossFront + lossBack;73 }74};75