r/learnpython • • 9m ago

leetcode 2926, TLE with both top down and bottom up approaches, what now

leetcode 2926

```py

class Solution:

def maxBalancedSubsequenceSum(self, nums: List[int]) -> int:

t = [nums[i] for i in range(len(nums))]

max_val = 0

for i in range(len(nums)):

for k in range(i):

if nums[k] - k <= nums[i] - i:

t[i] = max(t[i], t[k] + nums[i])

max_val = max(max_val, t[i])

return max_val if max(nums) > 0 else max(nums)

```

time limit exceeded how to fix? same error for top down as well

1 Upvotes

1 comment sorted by

•

u/Rare-Pay9795 0m ago

Your logic is right, it's just the nested loop that's O(n2), which is too slow for n up to 1e5. The condition nums[k] - k <= nums[i] - i means you only care about the key nums[i] - i, so for each i you need the best t[k] among all earlier k with a key <= yours. Do that with a Fenwick tree (BIT) for prefix max: compress the values of nums[i] - i, query the max over keys <= current key, add nums[i] to it (only if it's positive, otherwise just use nums[i]), then update the tree at your key. That brings it down to O(n log n). Also the answer is just the max over all dp values, so you can drop the special case at the end if you handle negatives that way.