Description

The window never changes size; you slide it and update by adding the new element / removing the one that fell off.
?

Reach for when

Max sum of k consecutive elements, averages of subarrays of size k.

Runtime

O(n)

Visualization

Fixed Sliding Window-1783988853691.webp

Pseudocode

current = compute(l, r)
for r in range(k, length(array)):
	l = r-k
	remove l from current
	add r to current
	update answer
return answer

Code

def max_sum_k(arr, k):
	window = sum(arr[:k])
	best = window
	for r in range(k, len(arr)):
		window += arr[r]
		window -= arr[r - k]
		best = max(best, window)
	return best