Watch a window of size k slide across the array, adding one value and dropping one, to find the maximum sum. Worked example with k = 3, or type your own array.
About this algorithm
The sliding window technique keeps a window over neighbouring values of an array and slides it one place at a time, so a sum over every run of k values takes O(n) instead of O(n × k). Each slide adds the value coming in on the right and subtracts the one leaving on the left, instead of adding up the whole window again. This page uses it to find the largest total of k values that sit next to each other.
Use a fixed window whenever the question names a block size: the best k day sales run, the busiest k minutes, a moving average over the last k readings. The idea is that neighbouring windows share all but two values, so recomputing them is wasted work. When the size is not fixed and depends on a condition, the variable window pages fit better: max consecutive ones and min window sum grow and shrink the window as they go. The gas station and max average pages under this heading solve their problems with binary search on the answer instead.
Add array[0] through array[k - 1]. That total is the first window's sum and also the best so far.
For i from k to n - 1, the new window gains array[i] and loses array[i - k]. Update the sum with windowSum += array[i] - array[i - k]. That is O(1) work instead of k additions.
If the new sum is strictly greater than the best, record it and where the window starts. A tie leaves the earlier window as the answer.
After the last slide, the best sum and its start index describe the answer: start to start + k - 1.
The page opens on [2, 1, 5, 2, 6, 2, 1, 4, 3, 5, 6, 2] with k = 3. The first window 2 + 1 + 5 = 8. Sliding: add 2, drop 2, still 8, a tie, so the best does not move. Add 6, drop 1: 13, the new best at indices 2 to 4. The next windows are 10, 9, 7, 8 and 12, all short of 13. Add 6, drop 4: 14 at indices 8 to 10 (3 + 5 + 6), the new best. The last slide gives 13. The answer is 14, found with 3 additions to build the first window and 9 slides, against 30 additions if every window were summed from scratch. Generate New rolls a random row if you want a different one.
A fixed window does not care about signs, because the size never depends on the values. The variable window pages are different: min window sum, for instance, relies on every value being positive.
Time: k additions to build the first window, then one add and one subtract for each of the n - k slides. Space: the running sum, the best sum and its index; the window is never copied.