Workspace Sliding Window
0d
DSA Cheat Sheets

Sliding window templates

For these maximum-sum examples require 1 ≤ k ≤ length. Initialize the best from a complete window to handle all-negative values.

Fixed widthSubtract the exiting valueAdd the entering value
Variable widthTrack a validity ruleRestore it by shrinking when justified
Half-open window [l,r)Length r − lInclusive [l,r] instead has length r − l + 1

Python

def best_window(a, k):
    total = best = sum(a[:k])
    for i in range(k, len(a)):
        total += a[i] - a[i-k]
        best = max(best, total)
    return best

C++

long long bestWindow(const std::vector<int>& a, int k) {
  long long sum = 0;
  for (int i = 0; i < k; ++i) sum += a[i];
  long long best = sum;
  for (int i = k; i < (int)a.size(); ++i) {
    sum += (long long)a[i] - a[i-k]; best = std::max(best, sum);
  }
  return best;
}

Java

static long bestWindow(int[] a, int k) {
  long sum = 0;
  for (int i = 0; i < k; i++) sum += a[i];
  long best = sum;
  for (int i = k; i < a.length; i++) {
    sum += (long)a[i] - a[i-k]; best = Math.max(best, sum);
  }
  return best;
}