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
- 41 lines of Python from the credited upstream file 2926.py.
- The implementation visibly relies on sequence storage.
- No explicit 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 def __init__(self, n: int):3 self.vals = [0] * (n + 1)4 5 def maximize(self, i: int, val: int) -> None:6 """Updates the maximum sum of subsequence ending in (i - 1) with `val`."""7 while i < len(self.vals):8 self.vals[i] = max(self.vals[i], val)9 i += FenwickTree.lowbit(i)10 11 def get(self, i: int) -> int:12 """Returns the maximum sum of subsequence ending in (i - 1)."""13 res = 014 while i > 0:15 res = max(res, self.vals[i])16 i -= FenwickTree.lowbit(i)17 return res18 19 @staticmethod20 def lowbit(i: int) -> int:21 return i & -i22 23 24class Solution:25 def maxBalancedSubsequenceSum(self, nums: list[int]) -> int:26 27 28 29 30 31 32 ans = -math.inf33 tree = FenwickTree(len(nums))34 35 for _, i in sorted([(num - i, i) for i, num in enumerate(nums)]):36 subseqSum = tree.get(i) + nums[i]37 tree.maximize(i + 1, subseqSum)38 ans = max(ans, subseqSum)39 40 return ans41