r/learnpython • u/TreacleFlaky2283 • 8h 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
0
Upvotes
1
u/Rare-Pay9795 7h 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.
•
u/InevitablePure4177 17m ago
Keep your original quadratic DP as a reference implementation, with max(t) as the return value. Compare the faster version against it on small random arrays before submitting. Include all-negative arrays and equal keys, for example [2, 3, 4], whose answer is 9. One caveat about plain sorted lists: bisect finds the position in logarithmic time, but inserting into a Python list can still take linear time. So that version can still time out.
1
u/MrCollab00ProfA00 6h ago
You don't actually have to learn Fenwick trees first for this one. In Python on LeetCode, you can use `SortedDict` (from `sortedcontainers`, which is pre-installed in LeetCode's Python 3 environment) to maintain a monotonic map of `key = nums[i] - i` -> `best_sum`.
The key idea: if an earlier index has a smaller-or-equal key AND a larger-or-equal sum than a later entry with a bigger key, that bigger key is strictly worse and can be deleted. That keeps `best_sum` strictly increasing with `key`, so you can just binary-search (`bisect_right`) for the largest key `<= k`:
Each element is inserted once and popped at most once, so it's O(n log n) without needing BIT indexing.