24/32
Part 6 of 6 · Follow-upsLearn and do

What about a total of at most a budget, with negative numbers?

That needs p >= total - budget, and a dict only looks up an exact value. The longest stretch ending here starts after the earliest prefix that's big enough.

Keep a running max of the prefix totals, called tops here. It never goes down, so a binary search finds the first place it reaches total - budget: check the middle of the sorted list, keep the half that can hold the answer, and repeat. Each check halves the range, so it takes about log₂ n checks, 20 for a million values. bisect_left(a, x) from Python's bisect module does it and returns the first index where a[i] >= x. The binary search lesson builds it by hand. At that point the prefix itself is big enough, and every prefix before it is too small. So the longest stretch starts right after it.

from bisect import bisect_left

def longest_within(values, budget):
    # tops[i]: the largest total of the first j values, for j <= i
    tops = [0]
    total = best = 0
    for right, v in enumerate(values):
        total += v
        # earliest prefix with p >= total - budget
        start = bisect_left(tops, total - budget)
        if start <= right:
            best = max(best, right + 1 - start)
        tops.append(max(tops[-1], total))
    return best

print(longest_within([5, -4, 3], 4))
3

Here is the last step on that list:

Values 5, -4, 3Prefix totalTop: the largest prefix so far
before index 000
after index 055
after index 115
after index 245

At index 2 the total is 4, so the stretch needs a prefix of at least 4 - 4 = 0 before it. The first top of at least 0 is before index 0, so the stretch is the whole list: length 3.

bisect_left(tops, x) from the bisect module is one binary search on a sorted list. The name isn't the point: any binary search works.

It matched checking every stretch on 5,000 random lists with negative numbers. One binary search per entry: O(n log n) time and O(n) memory.

Write the two pieces under longest_within: prefix_tops builds tops, and earliest_start is the binary search in it. The tests run longest_within on your two functions.