Sliding Window (Max Sum of k) visualization

Slide a fixed-size window: add the entering element, subtract the leaving one.

Recomputing each window from scratch is O(n·k). Sliding reuses the previous sum: new = old + A[i] − A[i−k], giving O(n).

Edge cases: k larger than n has no window; k = n has exactly one; with all-negative input the best is the least-negative window, so start best at the first window, not 0.

Complexity

Time: best O(n), average O(n), worst O(n). Space: O(1). Difficulty: Beginner.

Pseudocode

procedure maxWindow(A, k):
  if k ≤ 0 or k > n: return none
  sum ← A[0] + … + A[k−1]; best ← sum
  for i ← k to n−1:
    sum ← sum + A[i] − A[i−k]
    best ← max(best, sum)
  return best

More techniques algorithms