Problem 303471 · easy · Phase 03 Linear Management & Searching

Longest Stretch Under Budget

sliding window · variable-size window · two pointers

A road trip passes a list of toll booths with charges costs (all non-negative). You want to drive through as many consecutive booths as possible while paying at most budget in total. Return the length of the longest such run of booths, or 0 if even a single booth is too expensive.

Examples

Input:  costs = [3, 1, 2, 1, 4], budget = 4
Output: 3
Explanation: booths [1, 2, 1] cost exactly 4; no longer run fits.

Input:  costs = [5, 6], budget = 4
Output: 0

Input:  costs = [2, 2, 2], budget = 6
Output: 3

Constraints

  • 0 <= len(costs) <= 10**5
  • 0 <= costs[i] <= 10**4, 0 <= budget <= 10**9
  • Target complexity: O(n) time; checking every start/end pair (O(n²)) is too slow for the largest tests.

Goals

  • Grow a window on the right and shrink it on the left when a constraint breaks
  • Rely on non-negative values to keep the window sum monotone
Starting Python…