Approach
Sorting and greedy selection
For Maximum Balanced Subsequence Sum, 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
- 61 lines of C++ from the credited upstream file 2926.cpp.
- The implementation visibly relies on sequence storage.
- 4 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.
1class FenwickTree {2 public:3 FenwickTree(int n) : vals(n + 1) {}4 5 6 void maximize(int i, long val) {7 while (i < vals.size()) {8 vals[i] = max(vals[i], val);9 i += lowbit(i);10 }11 }12 13 14 long get(int i) const {15 long res = 0;16 while (i > 0) {17 res = max(res, vals[i]);18 i -= lowbit(i);19 }20 return res;21 }22 23 private:24 vector<long> vals;25 26 static int lowbit(int i) {27 return i & -i;28 }29};30 31class Solution {32 public:33 long long maxBalancedSubsequenceSum(vector<int>& nums) {34 35 36 37 38 39 40 long ans = LONG_MIN;41 FenwickTree tree(nums.size());42 43 for (const auto& [_, i] : getPairs(nums)) {44 const long subseqSum = tree.get(i) + nums[i];45 tree.maximize(i + 1, subseqSum);46 ans = max(ans, subseqSum);47 }48 49 return ans;50 }51 52 private:53 vector<pair<int, int>> getPairs(const vector<int>& nums) {54 vector<pair<int, int>> pairs;55 for (int i = 0; i < nums.size(); ++i)56 pairs.emplace_back(nums[i] - i, i);57 ranges::sort(pairs);58 return pairs;59 }60};61