Current Sum
0
Max Sum
0
2
0
1
1
5
2
1
3
3
4
2
5
9
6
8
7
3
8

The Moving Frame

Some problems ask us to look at a contiguous sub-part of an array. Instead of re-calculating everything, we can 'slide' a window over the data.

Create the Window

Let's find the max sum of any '3' consecutive numbers. We start by building the first window of size 3.

Efficient Movement

To move right, we DON'T need to sum 1+5+1 from scratch. We simply subtract the element the left LEFT (2) and add the element entering RIGHT (1).

Update Sum

8 - 2 + 1 = 7. The new sum is 7. Is it higher than our Max (8)? No.

Slide Again

Move right again. Subtract 1. Add 3.

And Again

Slide right. Subtract 5. Add 2. Sum: 6. Max stays 9.

Finding Gold

Slide right. Subtract 1. Add 9. Sum = 14! New Record.

Keeping Momentum

Slide right. Subtract 3. Add 8. Sum = 19! Even better.

Final Stretch

Last slide. Subtract 2. Add 3. Sum = 20. The winner is 20.

O(n) Efficiency

We touched each element only twice (once entering, once leaving). This is O(n), much faster than checking every subarray separately.

Optimization Gold.

Sliding Window turns nested loops O(n*k) into linear time O(n).

AlgoAnimator: Interactive Data Structures