Keep the useful overlap.
Reuse the overlap between consecutive fixed-length windows.
01 Model the idea
A sliding window avoids recalculating work shared by neighbouring ranges. For a fixed-size sum, moving one step removes the outgoing value and adds the incoming value. Initialise from a real window rather than zero so all-negative inputs remain correct. Variable-length windows need an additional invariant explaining when to expand or shrink; not every range problem has a monotonic shrink rule.
The running aggregate describes exactly the current valid window.
02 State the strategy
Read the steps independently of syntax. Explain what each step preserves before translating it into code.
SUM the first valid window
SUBTRACT outgoing and add incoming value per shift
UPDATE the best seen answer03 Make it concrete
The implementation uses Python 3.11+ with only the standard library. Run it locally, or download the independent DSA workbench.
def best_window(values, size):
if not 1 <= size <= len(values): raise ValueError("Valid positive window size required")
current = sum(values[i] for i in range(size))
best = current
for right in range(size, len(values)):
current += values[right] - values[right - size]
best = max(best, current)
return best
print(best_window([2, 1, 5, 1, 3, 2], 3))
print(best_window([-5, -2, -8], 2))9 -7
- 1
The generator-based initial sum avoids allocating a sliced list. The first actual window provides the baseline answer.
- 2
Each later iteration changes only two contributions. The current sum always represents exactly size consecutive values ending at right.
- 3
Returning the best range itself requires tracking its start when a new maximum is found. Define a tie rule if multiple windows share the same sum.
04 Count the cost
O(n)
O(1) auxiliary in shown main function
Bounds refer to the shown implementation and exclude printed output unless stated. n is input size; V and E are graph vertices and edges.
05 Your next move
Track the start index of a best two-element window.
Reveal one possible solution +
values, size = [1, 6, 2, 3], 2
current = sum(values[:size])
best, start = current, 0
for right in range(size, len(values)):
current += values[right] - values[right-size]
if current > best: best, start = current, right-size+1
print(start, best)06 Check your reasoning
What changes between neighbouring fixed-size windows?
Understand it. Then own it.
Can you explain the invariant, trace an edge case, and defend the cost model? Log the experiment when the reasoning makes sense.