Leetcode #2926: Maximum Balanced Subsequence Sum
In this guide, we solve Leetcode #2926 Maximum Balanced Subsequence Sum in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
You are given a 0-indexed integer array nums. A subsequence of nums having length k and consisting of indices i0 < i1 < ...
Quick Facts
- Difficulty: Hard
- Premium: No
- Tags: Binary Indexed Tree, Segment Tree, Array, Binary Search, Dynamic Programming
Intuition
The problem structure suggests a monotonic decision, which makes binary search a natural fit.
By halving the search space each step, we reach the answer efficiently.
Approach
Search either directly on a sorted array or on the answer space using a check function.
Each check is fast, and the logarithmic search keeps the overall runtime low.
Steps:
- Define the search bounds.
- Check the mid point condition.
- Narrow the bounds until convergence.
Example
Input: nums = [3,3,5,6]
Output: 14
Explanation: In this example, the subsequence [3,5,6] consisting of indices 0, 2, and 3 can be selected.
nums[2] - nums[0] >= 2 - 0.
nums[3] - nums[2] >= 3 - 2.
Hence, it is a balanced subsequence, and its sum is the maximum among the balanced subsequences of nums.
The subsequence consisting of indices 1, 2, and 3 is also valid.
It can be shown that it is not possible to get a balanced subsequence with a sum greater than 14.
Python Solution
class BinaryIndexedTree:
def __init__(self, n: int):
self.n = n
self.c = [-inf] * (n + 1)
def update(self, x: int, v: int):
while x <= self.n:
self.c[x] = max(self.c[x], v)
x += x & -x
def query(self, x: int) -> int:
mx = -inf
while x:
mx = max(mx, self.c[x])
x -= x & -x
return mx
class Solution:
def maxBalancedSubsequenceSum(self, nums: List[int]) -> int:
arr = [x - i for i, x in enumerate(nums)]
s = sorted(set(arr))
tree = BinaryIndexedTree(len(s))
for i, x in enumerate(nums):
j = bisect_left(s, x - i) + 1
v = max(tree.query(j), 0) + x
tree.update(j, v)
return tree.query(len(s))
Complexity
The time complexity is , and the space complexity is . The space complexity is .
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.