776. Find the longest run of log lines that fits a token budget
You want to send a model the longest unbroken run of log lines that fits in its token budget, so the summary sees as much connected context as possible.
Write longest_span(token_counts, budget). token_counts is a list of non-negative integers, the token count of each line in order. Return [length, start]: the length of the longest contiguous run whose total is at most budget, and the index where it starts. If several runs have the same length, return the one with the smallest start. If no line fits, return [0, 0].
def longest_span(token_counts, budget)Example 1
Input: longest_span([3, 1, 2, 7, 1, 1, 1], 6)
Output: [3, 0], from lines 0 to 2 (3 + 1 + 2 = 6)
Explanation: The run [1, 1, 1] at index 4 also has length 3 but starts later.
Example 2
Input: longest_span([9, 9], 5)
Output: [0, 0]
Example 3
Input: token_counts = [1, 2, 3], budget = 100
Output: [3, 0]
Constraints
- 0 <=
len(token_counts)<= 200,000 - Each count is an integer from 0 to 10^6
- 0 <= budget <= 10^12
Hint 1
Keep a running total instead of summing the window each time.
Hint 2
Shrink with a while loop, not an if.
Hint 3
Use a strict > when comparing lengths so ties keep the first run.
Common mistakes
- Recomputing the window sum on every step, which makes it O(n^2).
- Shrinking only once with an if, which leaves the window over budget.
- Returning the last best run on ties instead of the first.
Understand the idea
A sliding window keeps a range [left, right] and a running total. You move right one step at a time, and move left only when the range breaks the rule. For [3, 1, 2, 7] with budget 6, the window grows to [3, 1, 2] (total 6), then adding 7 makes 13, so left moves past 3, 1 and 2 and then past 7 too. Each element is added once and removed once, so the cost is O(n) instead of checking all O(n^2) ranges. It only works when the total moves in one direction as the window grows, which is why counts must be non-negative.