QuestionsDSA

Max Average Subarray (size k)

Sliding WindowEasyDSA

Find the contiguous subarray of length k with the maximum average, return that average.

What it tests

Fixed-size window: recognizing you don't recompute the sum each time.

Approach & answer

Compute the sum of the first k. Then slide: add the incoming element, subtract the outgoing one. Each step is O(1), so the whole thing is O(n) instead of O(n·k). The realization is that consecutive windows overlap in k−1 elements — recomputing the whole sum re-reads shared work you already did. Track the max sum and divide by k once at the end (dividing each step is wasteful and risks floating-point drift). Fixed-size windows are the gateway to the harder variable-size window template.

Use this technique when

'Best window of fixed length k' → maintain a running sum, add-one/drop-one as you slide.

Complexity

Time O(n) · Space O(1)

References

js