What is Sliding Window Algorithm? Examples?

ぃ、小莉子 提交于 2019-11-26 12:54:57

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

Devans Somani

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]);
        }
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!