Sliding window

Sliding window, also called two finger algorithm, is a technique of solving algorithmic problems by keeping invariants true by bounding endpoints.

A characteristic of a problem that can be solved with sliding windows is that an invariant is true with a left endpoint and a right endpoint, and can be held true as we slide the left and the right endpoints, often in a greedy fashion. This is common of problems that requires the result to be contiguous, i.e., longest consecutive that fits a certain criteria.

Maximum Subarray Sum

 * Given an array of size N, what is the maximal sum of k consecutive numbers?

For this problem, the naive solution is to start from each i, and then sum the next k elements, updating the current max as we go. This algorithm is $$O(kN)$$.

We can use sliding window to speed this up. Note the invariant for this problem is that we want to keep track of k consecutive elements, with two simultaneous events - moving our left pointer to the right, and moving our right pointer to the right. Defining $$s_{i,j}$$ as the sum between the indices i and j of an array a, and that $$j - i + 1 = k$$, notice that the sum $$s_{i,j} = a_i + a_{i+1} + \ldots + a_j$$ and $$s_{i+1,j+1} = a_{i+1} + \ldots + a_{j} + a_{j+1}$$ differs only slightly - in fact, $$s_{i+1,j+1} - s_{i,j} = a_{j+1} - a_i$$. Now we can calculate $$s_{i+1,j+1} = s_{i,j} + a_{j+1} - a_i$$.

For $$N = 10$$, $$k = 3$$ [(50 4 39) 20 23 14 10 5 47 31] -> window sum is 93 to [50 (4 39 20) 23 14 10 5 47 31] -> window sum is 93 - 50 + 20 = 63

Pseudocode
 def max_subarray_sum(arr, k) N := len(arr) max_sum := -∞

for i from 0 to N - k - 1 current_sum = 0 for j from 0 to k - 1 current_sum += arr[i+j] if current_sum > max_sum, set max_sum t= current_sum return max_sum  def max_subarray_sum(arr, k) N := len(arr) max_sum := -∞ set_count := 0 current_sum := 0

for i from 0 to N - 1 current_sum += arr[i] set_count += 1

if set_count > k     current_sum -= arr[i-k+1] # now set_count should be k again set_count -= 1 if current_sum > max_sum, set max_sum t= current_sum return max_sum

Related Problems

 * Leetcode 3