Skip to content

Commit

Permalink
Created sliding_window_max_of_all_subarrays.cpp
Browse files Browse the repository at this point in the history
This code will find the maximum elements in all sub-arrays of size 'k' in an array. Double-ended Queue data structure is used here using CPP STL.
  • Loading branch information
shadowfax999 authored Oct 1, 2021
1 parent 769c6e5 commit 282a3ac
Showing 1 changed file with 42 additions and 0 deletions.
42 changes: 42 additions & 0 deletions sliding_window_max_of_all_subarrays.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
#include <bits/stdc++.h>
#include <deque>
using namespace std;

//Main Function Block
void printKMax(int arr[], int n, int k)
{
deque<int> dq(k);
for (int i = 0; i < k; ++i)
{
while ((!dq.empty()) && arr[i] >= arr[dq.back()])
dq.pop_back();

dq.push_back(i);
}

for (; i < n; ++i)
{
cout << arr[dq.front()] << " ";

while ((!dq.empty()) && dq.front() <= i - k)

dq.pop_front();

while ((!dq.empty()) && arr[i] >= arr[dq.back()])
dq.pop_back();

dq.push_back(i);
}

cout << arr[dq.front()];
}

//Testing code
int main()
{
int arr[] = { 12, 156, 73, 93, 59, 83, 51, 73, 101, 456};
int n = sizeof(arr) / sizeof(arr[0]);
int k = 3;
printKMax(arr, n, k);
return 0;
}

0 comments on commit 282a3ac

Please sign in to comment.