Maximum Balanced Subsequence Sum - Problem

You're given a 0-indexed integer array nums and need to find the maximum sum of a special type of subsequence called a balanced subsequence.

A subsequence with indices i₀ < i₁ < ... < iₖ₋₁ is balanced if for every consecutive pair of elements:

nums[iⱼ] - nums[iⱼ₋₁] ≥ iⱼ - iⱼ₋₁ for all j ∈ [1, k-1]

In simpler terms, the value difference between consecutive elements must be at least as large as their index difference. This ensures the subsequence grows "fast enough" relative to how spread out the indices are.

Goal: Return the maximum possible sum of elements in any balanced subsequence. Note that a single element is always considered balanced.

Example: For nums = [3, -1, 1, 2], the subsequence at indices [0, 3] gives us [3, 2]. Check: 2 - 3 = -1 and 3 - 0 = 3, so -1 ≥ 3 is false, making this not balanced.

Input & Output

example_1.py — Basic case with mixed values
$ Input: nums = [3, -1, 1, 2]
Output: 3
💡 Note: The best balanced subsequence is just the single element [3] at index 0. Other subsequences like [3, 2] fail the balance check: (2-3) = -1 < (3-0) = 3.
example_2.py — All negative values
$ Input: nums = [-1, -2, -3]
Output: -1
💡 Note: Since all values are negative, the best strategy is to pick the single largest element, which is -1 at index 0.
example_3.py — Increasing subsequence
$ Input: nums = [5, 6, 7, 8]
Output: 26
💡 Note: The entire array forms a balanced subsequence: differences are [1,1,1] and index gaps are [1,1,1], so 1 ≥ 1 for all pairs. Sum = 5+6+7+8 = 26.

Constraints

  • 1 ≤ nums.length ≤ 105
  • -109 ≤ nums[i] ≤ 109
  • The subsequence must maintain original relative order of elements

Visualization

Tap to expand
Mountain Climbing Analogy3Peak 1-1Peak 21Peak 32Peak 4Balance Condition CheckTo climb from Peak i to Peak j: (height_j - height_i) ≥ (distance_j - distance_i)Ensures sufficient elevation gain relative to travel distanceOptimal StrategyUse DP with segment tree to efficiently find the best previous peak that satisfies climbing constraints
Understanding the Visualization
1
Transform Problem
Convert balance condition to: transformed[j] ≥ transformed[i] where transformed[k] = nums[k] - k
2
Coordinate Compression
Map potentially large value ranges to compact array indices for efficient processing
3
Dynamic Programming
Use segment tree to quickly find the best previous position that satisfies the constraint
4
Optimal Selection
Build up the maximum sum by considering each position and its optimal predecessors
Key Takeaway
🎯 Key Insight: Transform the balance condition algebraically and use advanced data structures to handle the complex constraint efficiently in O(n log n) time.
Asked in
Google 12 Microsoft 8 Amazon 6 Meta 4
26.3K Views
Medium Frequency
~35 min Avg. Time
856 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