Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Enquire Book a call

Coding · Sliding window

Longest run of tasks within a time budget

Easy · Target 12 minutes · Sliding window· Type asked at

times[i] is the number of minutes task i takes, always positive. Tasks must be done in a consecutive run. Return the largest number of consecutive tasks whose total time is at most budget.

Examples

InputOutputWhy
times = [3,1,2,7,4,2,1,1,5], budget = 844 + 2 + 1 + 1.
times = [5,5,5], budget = 40No single task fits.
times = [1,1,1], budget = 103

Constraints

  • 1 ≤ n ≤ 10⁵
  • 1 ≤ times[i] ≤ 10⁴
  • 0 ≤ budget ≤ 10⁹

Hints

Hint 1

Every time is positive. What happens to a run's total when you add a task to it, or remove one from its start?

Hint 2

If the run from lo to hi is over budget, so is every run from lo that ends later.

Hint 3

Grow on the right; while the total exceeds the budget, drop tasks from the left.

Where people lose marks

  • Applying the same code to arrays with negative numbers. It gives wrong answers without any error.
  • Shrinking past hi when a single task exceeds the budget: the loop must stop when the window is empty.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.