You are given an integer array nums. A subsequence is considered "balanced" if, for every adjacent pair of elements nums[i] and nums[j] in the subsequence (where ), the condition nums[j] - nums[i] >= j - i holds true. Your goal is to find the maximum possible sum of any balanced subsequence.
This is a Hard-level Dynamic Programming problem that masks a beautiful mathematical trick. Interviewers ask it to separate candidates who write standard LIS (Longest Increasing Subsequence) templates from those who can algebraically manipulate the constraint. It tests your ability to use advanced data structures like Segment Trees or Binary Indexed Trees (BIT) to optimize DP lookups.
This relies on Algebraic Rearrangement and a Segment Tree / BIT for DP Optimization.
nums[j] - nums[i] >= j - i translates perfectly to nums[j] - j >= nums[i] - i.val[i] = nums[i] - i. The problem is now identical to finding the Maximum Sum Increasing Subsequence based on this new val array! (You can only append nums[j] to nums[i] if val[j] >= val[i]).nums[i]), standard DP is too slow. We compress/sort the unique vals and use a Segment Tree or BIT. The tree will store the maximum sum achievable for a given val. We query the tree for the max sum of all values , add nums[i] (if it's positive), and update the tree.Array nums = [3, 3, 5, 6]
val[i] = nums[i] - i:
idx 0: .idx 1: .idx 2: .idx 3: .
val array: [3, 2, 3, 3].val[i] >= val[prev]:
num=3, val=3: Max sum is 0. New sum = 3. Update tree at 3 with 3.num=3, val=2: Max sum is 0. New sum = 3. Update tree at 2 with 3.num=5, val=3: Max sum is 3 (from the first 3). New sum = . Update tree at 3 with 8.num=6, val=3: Max sum is 8 (from the 5). New sum = . Update tree at 3 with 14.
The maximum balanced subsequence sum is 14 ([3, 5, 6]).The most critical mistake is failing to rearrange the inequality. If you leave it as nums[j] - nums[i] >= j - i, the dependencies are tangled, and you are forced into an loop. Decoupling the j terms from the i terms is the only way to enable logarithmic data structures. Another mistake is including negative numbers in the sequence; if nums[i] is negative, it only hurts the sum, so it should be skipped unless the array is entirely negative (in which case, just return the max single negative element).
When an interview problem gives you a constraint inequality involving two different array indices like A[j] - A[i] >= B[j] - B[i], always group the terms by index. Rewrite it as A[j] - B[j] >= A[i] - B[i]. This isolates the property to a single element, transforming an pairwise relationship into a much simpler sorting or tree-based property check.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Subarrays Distinct Element Sum of Squares II | Hard | Solve | |
| Block Placement Queries | Hard | Solve | |
| Count Number of Teams | Medium | Solve | |
| Number of Longest Increasing Subsequence | Medium | Solve | |
| Online Majority Element In Subarray | Hard | Solve |