Reqflow
Sliding Window·Intermediate

Sliding Window: Max Sum

Time O(n)Space O(1)
·

Find the largest sum of any k consecutive elements. The naive approach recomputes each window's sum, which is O(n times k). The sliding window keeps a running sum: when you move the window one step right, you add the new element on the right and subtract the one that fell off the left. Each slide is constant work, so the whole scan is linear.

Example: Largest sum of 3 elements in a row.

When to use this

See also

← All algorithms