Video in progress
How do you find the maximum sum of k consecutive elements in an array?
With a sliding window: I compute the sum of the first k elements, and as the window moves by one I add the new element and subtract the one that left. Each step is O(1), so the total is O(n); re-summing every window would be O(n·k).
📖 Answer
static long maxWindowSum(int[] a, int k) {
if (k <= 0 || k > a.length) throw new IllegalArgumentException();
long window = 0;
for (int i = 0; i < k; i++) window += a[i];
long best = window;
for (int i = k; i < a.length; i++) {
window += a[i] - a[i - k]; // one came in, one went out
best = Math.max(best, window);
}
return best;
}
This is a fixed-size window. A real example: "the best 7-day period in daily sales" or "the most requests in a 5-minute window".
Why long? In an int array of a million elements, the sum may not fit into an int. The overflow passes silently and the result is simply wrong.
A variable-size window works differently: the right edge expands, and if the condition breaks, the left edge shrinks. For example, "the shortest subarray whose sum is greater than S", but that is correct only with positive numbers; with negative numbers you need a prefix sum.
Sign up to mark studied questions and save your progress.