#2926
Maximum Balanced Subsequence Sum
HardArrayBinary SearchDynamic ProgrammingBinary Indexed TreeSegment TreeDynamic ProgrammingArray Manipulation
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal 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- 1Step 1: Create an array dp where dp[i] represents the maximum sum of a balanced subsequence ending at index i.
- 2Step 2: Initialize dp[i] with nums[i] for all i.
- 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.
- 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.