Approach
Sorting and greedy selection
For Maximum Value of Concatenated Binary Segments, the implementation first exposes a useful order, then scans that order while making locally justified choices.
- Choose the key that reveals the greedy or grouping structure.
- Sort the relevant records by that key.
- Scan in order, maintaining the invariant that makes each local choice safe.
Code notes
- 38 lines of C++ from the credited upstream file maximum-value-of-concatenated-binary-segments.cpp.
- The implementation visibly relies on sequence storage.
- 3 loop blocks detected.
Complexity
Sorting is typically the dominant term unless the subsequent scan uses a more expensive nested operation.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
123 45const int MOD = 1e9 + 7;6const auto& precompute = [](int r) {7 vector<int64_t> pow2(r + 1, 1);8 for (int i = 0; i + 1 < size(pow2); ++i) {9 pow2[i + 1] = (pow2[i] * 2) % MOD;10 }11 return pow2;12};13 14const int MAX_TOTAL = 2e5;15const auto& POW2 = precompute(MAX_TOTAL);16class Solution {17public:18 int maxValue(vector<int>& nums1, vector<int>& nums0) {19 vector<pair<int, int>> segments;20 int l = 0;21 for (int i = 0; i < size(nums1); ++i) {22 if (nums0[i]) {23 segments.emplace_back(nums1[i], nums0[i]);24 } else {25 l += nums1[i];26 }27 }28 sort(begin(segments), end(segments), [](const auto& x, const auto& y) {29 return x.first == y.first ? x.second < y.second : x.first > y.first;30 });31 int64_t result = ((POW2[l] - 1) + MOD) % MOD;32 for (const auto& [cnt1, cnt0] : segments) {33 result = ((result * POW2[cnt1 + cnt0]) % MOD + ((((POW2[cnt1] - 1) + MOD) % MOD) * POW2[cnt0]) % MOD) % MOD;34 }35 return result;36 }37};38