#2926

Maximum Balanced Subsequence Sum

Hard
ArrayBinary SearchDynamic ProgrammingBinary Indexed TreeSegment TreeDynamic ProgrammingArray Manipulation
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n²)
Space
O(1)
O(n)
💡

Intuition

Time O(n²)Space O(n)

The optimal approach uses dynamic programming to build up the maximum sum of balanced subsequences efficiently. By transforming the balance condition, we can track the best sums in a single pass.

⚙️

Algorithm

4 steps
  1. 1Step 1: Create an array dp where dp[i] represents the maximum sum of a balanced subsequence ending at index i.
  2. 2Step 2: Initialize dp[i] with nums[i] for all i.
  3. 3Step 3: Iterate through the array, and for each index i, check all previous indices j to see if the balance condition holds and update dp[i] accordingly.
  4. 4Step 4: The result is the maximum value in the dp array.
solution.py14 lines
1# Full working Python code
2
3def max_balanced_subseq_sum(nums):
4    n = len(nums)
5    dp = [0] * n
6    for i in range(n):
7        dp[i] = nums[i]  # Start with the current element
8        for j in range(i):
9            if nums[i] - i >= nums[j] - j:  # Check balance condition
10                dp[i] = max(dp[i], dp[j] + nums[i])
11    return max(dp)
12
13# Example usage:
14print(max_balanced_subseq_sum([3, 3, 5, 6]))  # Output: 14

Complexity note: The time complexity is O(n²) due to the nested loop for checking previous indices, but we only store results for each index, leading to linear space complexity.

  • 1Transforming the balance condition allows for more efficient tracking of sums.
  • 2Dynamic programming helps in building solutions incrementally, reducing redundant calculations.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.