KatInterview

Peak Request Load Over a Fixed Run of Minutes

Arrays & HashingAuto-graded · 20 test cases
EasyAuto-gradedArrays & Hashingsliding-windowarraysprefix-sum

Last updated

Find the largest total of any k consecutive values in a list, testing fixed-size sliding window technique and the ability to avoid recomputing overlapping sums.

Peak Request Load Over a Fixed Run of Minutes

A service logs how many requests it receives during each minute, in chronological order. You want to know the busiest stretch of exactly k back-to-back minutes.

Write a function that takes the per-minute request counts and the stretch length k, and returns the greatest total number of requests found in any block of k consecutive minutes.

Details

  • A block is a run of k neighboring entries in the list, with no gaps and no reordering.
  • Blocks may overlap with each other. Every starting position that leaves room for k entries must be considered.
  • Return only the total, as a single integer. You do not need to report where the block begins.
  • If several blocks tie for the largest total, the answer is simply that shared total.
  • If k equals the length of the list, the only block is the whole list, so return the sum of all entries.
  • If k is 1, the answer is the largest single entry.

Constraints

  • counts is a list of positive integers.
  • 1 <= k <= len(counts)
  • The input is always valid, so you do not need to validate k.
  • Aim for time proportional to len(counts), rather than recomputing every block's sum from scratch.

Examples

Example 1

Input: peak_window_total([1, 2, 3, 4, 5], 2)

Output: 9

Example 2

Input: peak_window_total([2, 1, 5, 1, 3, 2], 3)

Output: 9

Example 3

Input: peak_window_total([5, 5, 5, 5], 2)

Output: 10

Hints

Hint 1

Adding up every block separately repeats a lot of work, because neighboring blocks share all but one element on each side.

Hint 2

When the block shifts one position to the right, exactly one value enters on the right and exactly one value leaves on the left. Update the running total using only those two values.

Hint 3

Compute the total of the first k entries to start, then slide across the rest of the list while tracking the largest total seen. This needs only a few variables beyond the input.