r/learnpython • • 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

5 comments sorted by

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.

1

u/TreacleFlaky2283 7h ago

but i haven't studied fenwick tree and it sounds a bit tough on what next to do

1

u/Rare-Pay9795 5h ago

No need for a Fenwick tree to get started. The core idea is that for each i you only need the best total among earlier elements whose key (nums[i] - i) is <= your key. A simpler way is to keep a sorted list of keys alongside the best sums, and use bisect to find the last key <= yours. When you insert a new entry, drop any entries with a larger key but a smaller or equal sum, so the sums stay increasing and the answer is always the entry just before your position. Fenwick is really just "prefix max in log n", so it's worth learning later once this version makes sense.

•

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`:

from sortedcontainers import SortedDict

class Solution:
    def maxBalancedSubsequenceSum(self, nums: List\[int\]) -> int:
        if max(nums) <= 0:
            return max(nums)
        dp = SortedDict()  # key: nums\[i\] - i, value: strictly increasing best sum
        for i, x in enumerate(nums):
            if x <= 0:
                continue  # negative/zero elements never improve a positive sum
            k = x - i
            idx = dp.bisect_right(k) - 1
            cur = x + (dp.values()\[idx\] if idx >= 0 else 0)
            dp\[k\] = cur
            # Remove any larger keys whose sum <= cur
            j = dp.bisect_right(k)
            while j < len(dp) and dp.values()\[j\] <= cur:
                dp.popitem(j)
        return max(dp.values())

Each element is inserted once and popped at most once, so it's O(n log n) without needing BIT indexing.