Maximum Number of all Fixed Size Sub-array(Sliding Window Technique)

/*
if window size is 3
and array is : 0 5 5 3 10 0 4

sub-array are ------> Maximum number
[0 5 5]   ------> 5
[5 5 3]   ------> 5
[5 3 10]  ------>   10
[3 10 0]  ------>   10
[10 0 4]  ------> 10
*/

#include<bits/stdc++.h>
#define p pair<int, int>
using namespace std;

void maximum_number(int a[], int n, int sz)
{
deque<p> w; /// w means Window

for(int i=0;i<n;i++)
{
while(!w.empty() && w.back().first <= a[i])
w.pop_back();

w.push_back(p(a[i], i));

while(w.front().second <= i-sz)
w.pop_front();

if(i+1 >= sz)
cout << w.front().first << "\n";
}
}

int main()
{
int n, sz;

    cout << "Enter Array Size :: ";
    cin >> n;

    cout << "\nEnter Window Size :: ";
    cin >> sz;

    int a[n]; /// declar a array

    cout << "\nEnter Array Element :: ";
    for(int i=0;i<n;i++)  /// Array :: 0 5 5 3 10 0 4
cin >> a[i];
cout << "\n";

cout << "Maximum Number are :: \n";
maximum_number(a, n, sz);

return 0;
}

Comments