Maximum Balanced Subsequence Sum - Problem

You are given a 0-indexed integer array nums. A subsequence of nums having length k and consisting of indices i₀ < i₁ < ... < iₖ₋₁ is balanced if the following holds:

nums[iⱼ] - nums[iⱼ₋₁] >= iⱼ - iⱼ₋₁, for every j in the range [1, k - 1].

A subsequence of nums having length 1 is considered balanced.

Return an integer denoting the maximum possible sum of elements in a balanced subsequence of nums.

A subsequence of an array is a new non-empty array that is formed from the original array by deleting some (possibly none) of the elements without disturbing the relative positions of the remaining elements.

Input & Output

Example 1 — Basic Balanced Subsequence
$ Input: nums = [3,4,5,1]
Output: 12
💡 Note: The balanced subsequence [3,4,5] at indices [0,1,2] gives maximum sum. Check: 4-3 ≥ 1-0 (1≥1 ✓), 5-4 ≥ 2-1 (1≥1 ✓). Sum = 3+4+5 = 12.
Example 2 — Single Element Maximum
$ Input: nums = [-1,-2,-3]
Output: -1
💡 Note: All single elements are balanced. The maximum single element is -1, so return -1.
Example 3 — Non-consecutive Subsequence
$ Input: nums = [5,-1,-3,8]
Output: 13
💡 Note: The balanced subsequence [5,8] at indices [0,3] gives maximum sum. Check: 8-5 ≥ 3-0 (3≥3 ✓). Sum = 5+8 = 13.

Constraints

  • 1 ≤ nums.length ≤ 105
  • -109 ≤ nums[i] ≤ 109

Visualization

Tap to expand
Maximum Balanced Subsequence Sum INPUT nums array: i=0 i=1 i=2 i=3 3 4 5 1 Balance Condition: nums[j] - nums[i] >= j - i Transform: nums[i] - i 3 3 3 -2 (3-0, 4-1, 5-2, 1-3) Input: [3, 4, 5, 1] ALGORITHM STEPS 1 Transform Array Compute b[i] = nums[i] - i 2 Use Segment Tree For max query in range 3 DP with Optimization dp[i] = max sum ending at i 4 Process Each Element Query + Update tree DP Computation: i=0: dp[0] = 3 i=1: dp[1] = 3+4 = 7 i=2: dp[2] = 7+5 = 12 i=3: dp[3] = 1 (reset) max(dp) = 12 FINAL RESULT Optimal Balanced Subsequence: i=0 3 i=1 4 i=2 5 Balance Check: 4-3 >= 1-0 : 1 >= 1 OK 5-4 >= 2-1 : 1 >= 1 OK All conditions satisfied! Sum Calculation: 3 + 4 + 5 = 12 Output: 12 Key Insight: The balance condition nums[j] - nums[i] >= j - i transforms to nums[j] - j >= nums[i] - i. By defining b[i] = nums[i] - i, we only need b[j] >= b[i] for valid transitions, enabling efficient O(n log n) solution using segment tree for range maximum queries. TutorialsPoint - Maximum Balanced Subsequence Sum | Optimal Solution
Asked in
Google 25 Microsoft 20 Amazon 15 Meta 12
12.5K Views
Medium Frequency
~35 min Avg. Time
342 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen