While solving a geometry problem, I came across an approach called Sliding Window Algorithm.
Couldn't really find any study material/details on it.
What is the algorithm about?
Generally speaking a sliding window is a sub-list that runs over an underlying collection. I.e., if you have an array like
[a b c d e f g h]
a sliding window of size 3 would run over it like
[a b c]
[b c d]
[c d e]
[d e f]
[e f g]
[f g h]
This is useful if you for instance want to compute a running average, or if you want to create a set of all adjacent pairs etc.
Sliding window is a problem solving technique for problems involves arrays/lists. these problems are easy to solve in brute force approach in O(n^2) or O(n^3) but making them solvable in O(n) requires more sophisticated approach.
Great article on this is here: https://medium.com/outco/how-to-solve-sliding-window-problems-28d67601a66
This is the code of the sliding window protocol for an array of size n, where sum of k numbers is stored together in another array sum.The following code is in Java.
import java.io.*;
class deva
{
public static void main(String args[])throws IOException
{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(in.readLine());
int[] a = new int[n];
for(int i=0; i<n; i++)
a[i] = Integer.parseInt(in.readLine());
int k = Integer.parseInt(in.readLine());
int[] sum = new int[n-k+1];
for(int i=0; i<k; i++)
sum[0] += a[i];
System.out.println(sum[0]);
for(int i=1; i<n-k+1; i++)
{
sum[i] = sum[i-1] + a[i+k-1] - a[i-1];
System.out.println(sum[i]);
}
}
}
来源:https://stackoverflow.com/questions/8269916/what-is-sliding-window-algorithm-examples