Imagine a frame that shows three boxes at a time. When the frame moves one step, two boxes stay inside. A sliding window reuses what those boxes already told us.
Remove one, add one
To find the largest sum of three neighboring numbers, first add the first three. Then subtract the number leaving the window and add the number entering it.
- Fixed windows always hold the same number of items.
- Flexible windows grow and shrink to obey a rule.
- The window usually represents one continuous section.
Avoid repeated addition
def best_three(numbers):
window = sum(numbers[:3])
best = window
for right in range(3, len(numbers)):
window += numbers[right]
window -= numbers[right - 3]
best = max(best, window)
return best
print(best_three([2, 1, 5, 3, 2])) # 9Every number enters and leaves the window at most once. That turns repeated work into one O(n) walk.
Look for words such as consecutive, continuous, substring, or subarray. They often point toward a sliding window.
Your tiny challenge
Write down the sums of every two neighboring numbers in 3, 1, 4, 2. Update the old sum instead of adding both numbers again.
