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
- 60 lines of Java from the credited upstream file 2926.java.
- 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 FenwickTree(int n) {3 vals = new long[n + 1];4 }5 6 7 public void maximize(int i, long val) {8 while (i < vals.length) {9 vals[i] = Math.max(vals[i], val);10 i += lowbit(i);11 }12 }13 14 15 public long get(int i) {16 long res = 0;17 while (i > 0) {18 res = Math.max(res, vals[i]);19 i -= lowbit(i);20 }21 return res;22 }23 24 private long[] vals;25 26 private static int lowbit(int i) {27 return i & -i;28 }29}30 31class Solution {32 public long maxBalancedSubsequenceSum(int[] nums) {33 34 35 36 37 38 39 long ans = Long.MIN_VALUE;40 FenwickTree tree = new FenwickTree(nums.length);41 42 for (Pair<Integer, Integer> pair : getPairs(nums)) {43 final int i = pair.getValue();44 final long subseqSum = tree.get(i) + nums[i];45 tree.maximize(i + 1, subseqSum);46 ans = Math.max(ans, subseqSum);47 }48 49 return ans;50 }51 52 private List<Pair<Integer, Integer>> getPairs(int[] nums) {53 List<Pair<Integer, Integer>> pairs = new ArrayList<>();54 for (int i = 0; i < nums.length; ++i)55 pairs.add(new Pair<>(nums[i] - i, i));56 pairs.sort((p1, p2) -> p1.getKey() - p2.getKey());57 return pairs;58 }59}60