Maximum sum of a subarray of size K (fixed sliding window). Compare brute force, prefix sums and the sliding window.
Problem
nums = [2, 1, 5, 1, 3, 2], k = 3 → 9 ([5, 1, 3]).
Pattern
Fixed-size sliding window: when the window moves one step, add the entering element and subtract the leaving one instead of recomputing. Template: build the first window, then slide.
Approach 1: Recompute every window (feasible, O(n·k))
java
class WindowSumBrute {
static int maxSum(int[] a, int k) {
int best = Integer.MIN_VALUE;
for (int i = 0; i + k <= a.length; i++) {
int sum = 0;
for (int j = i; j < i + k; j++) sum += a[j];
best = Math.max(best, sum);
}
return best;
}
}Approach 2: Prefix sums (O(n) time, O(n) space)
java
class WindowSumPrefix {
static int maxSum(int[] a, int k) {
int[] prefix = new int[a.length + 1];
for (int i = 0; i < a.length; i++) prefix[i + 1] = prefix[i] + a[i];
int best = Integer.MIN_VALUE;
for (int i = k; i <= a.length; i++) best = Math.max(best, prefix[i] - prefix[i - k]);
return best;
}
}Approach 3: Sliding window (O(n) time, O(1) space) — optimal
java
class WindowSumSliding {
static int maxSum(int[] a, int k) {
int sum = 0;
for (int i = 0; i < k; i++) sum += a[i]; // first window
int best = sum;
for (int i = k; i < a.length; i++) {
sum += a[i] - a[i - k]; // add entering, remove leaving
best = Math.max(best, sum);
}
return best;
}
}
class WindowSumDemo {
public static void main(String[] args) {
int[] a = {2, 1, 5, 1, 3, 2};
System.out.println(WindowSumBrute.maxSum(a, 3) + " " + WindowSumPrefix.maxSum(a, 3) + " " + WindowSumSliding.maxSum(a, 3)); // 9 9 9
}
}Feasible → optimal
O(n·k) recomputation → O(n) with prefix sums (extra array) → O(n), O(1) with a running window sum.
Follow-up questions interviewers ask
Try answering each one before you open it.
Related (same pattern): average of every window of size k, or count windows with average ≥ threshold.
Same running sum; divide by k (or compare sum >= threshold * k to stay in integers). O(n).
Related (same pattern): first negative number in every window of size k.
Keep a deque of indices of negative numbers inside the window; drop the head when it leaves the window; the head is the answer for each window. O(n).