- 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
- 51 lines of C++ from the credited upstream file maximum-total-value.cpp.
- The implementation visibly relies on sequence storage.
- 2 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.
123 45class Solution {6public:7 int maxTotalValue(vector<int>& value, vector<int>& decay, int m) {8 static const int MOD = 1e9 + 7;9 10 const auto& binary_search = [](int left, int right, const auto& check) {11 while (left <= right) {12 const auto& mid = left + (right - left) / 2;13 if (check(mid)) {14 right = mid - 1;15 } else {16 left = mid + 1;17 }18 }19 return left;20 };21 22 const auto& total = [&](int x) {23 int result = 0;24 int64_t cnt = 0;25 for (int i = 0; i < size(value); ++i) {26 if (value[i] - x < 0) {27 continue;28 }29 const int64_t t = (value[i] - x) / decay[i] + 1;30 result = t % 2 == 031 ? (result + (value[i] + (value[i] - decay[i] * (t - 1))) * (t / 2)) % MOD32 : (result + (value[i] - decay[i] * ((t - 1) / 2)) * t) % MOD;33 cnt += t;34 }35 return pair(result, cnt);36 };37 38 const auto& check = [&](int x) {39 return total(x).second <= m;40 };41 42 if (check(1)) {43 return total(1).first;44 }45 const auto& x = binary_search(2, ranges::max(value), check);46 auto [result, cnt] = total(x);47 result = (result + (m - cnt) * (x - 1)) % MOD;48 return result;49 }50};51