- 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
- 56 lines of C++ from the credited upstream file 2234.cpp.
- The implementation visibly relies on sequence storage.
- 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 long long maximumBeauty(vector<int>& flowers, long long newFlowers,4 int target, int full, int partial) {5 const int n = flowers.size();6 7 8 for (int& flower : flowers)9 flower = min(flower, target);10 ranges::sort(flowers);11 12 13 if (flowers[0] == target)14 return static_cast<long>(n) * full;15 16 17 if (newFlowers >= static_cast<long>(n) * target -18 accumulate(flowers.begin(), flowers.end(), 0L))19 return max(static_cast<long>(n) * full,20 (n - 1L) * full + (target - 1L) * partial);21 22 long ans = 0;23 long leftFlowers = newFlowers;24 25 vector<long> cost(n);26 27 for (int i = 1; i < n; ++i)28 29 cost[i] =30 cost[i - 1] + static_cast<long>(i) * (flowers[i] - flowers[i - 1]);31 32 int i = n - 1; 33 while (flowers[i] == target)34 --i;35 36 for (; leftFlowers >= 0; --i) {37 38 39 40 41 const int j = firstGreater(cost, i, leftFlowers);42 const long minIncomplete =43 flowers[j - 1] + (leftFlowers - cost[j - 1]) / j;44 ans = max(ans, (n - 1L - i) * full + minIncomplete * partial);45 leftFlowers -= max(0, target - flowers[i]);46 }47 48 return ans;49 }50 51 private:52 int firstGreater(const vector<long>& A, int maxIndex, long target) {53 return upper_bound(A.begin(), A.begin() + maxIndex + 1, target) - A.begin();54 }55};56