Given a set of arrays of size and an integer , you have to find the maximum integer for each and
every contiguous subarray of size for each of the given arrays.
Input Format
First line of input will contain the number of test cases T. For each test case, you will be given the size of
array N and the size of subarray to be used K. This will be followed by the elements of the array A .
Constraints
, where is the element in the array .
Output Format
For each of the contiguous subarrays of size of each array, you have to print the maximum integer.
Sample Input
i
2
5 2
3 4 6 3 4
7 4
3 4 5 8 1 4 10
Sample Output
4 6 6 4
8 8 8 10
Explanation
For the first case, the contiguous subarrays of size 2 are {3,4},{4,6},{6,3} and {3,4}. The 4 maximum
elements of subarray of size 2 are: 4 6 6 4.
For the second case,the contiguous subarrays of size 4 are {3,4,5,8},{4,5,8,1},{5,8,1,4} and {8,1,4,10}.
The 4 maximum element of subarray of size 4 are: 8 8 8 10.
I'm struggling with a question on hackerrank. I have implemented an algorithm which finds the maximum element in the windows and stores its index, then use this index of the maximum element in the previous window to find the maximum element in the next window only if the index of maximum element lies between the indexes of the next window. I've tried many test cases but i'm still unable to figure out the error in the code.
What I have tried:
using namespace std;
#include<iostream>
#include<algorithm>
int m,idx,ct=0;
void maxinwindow(int arr[], int start, int end)
{
if(idx>=start)
{
if(arr[idx]>=arr[end])
{
if(arr[idx]==arr[end])
{
idx=end;
}
m=arr[idx];
}
else
{
m=arr[end];
idx=end;
}
}
else
{
if(arr[start]>=arr[start+1])
{
m=arr[start];
}
else
{
m=arr[start+1];
}
for(int k=start+2;k<=end;k++)
{
if(arr[k]>=m)
{
m=arr[k];
idx=k;
}
}
}
}
int main()
{
int arr[100000];
int q;
cin>>q;
for(int i=1,size,ws;i<=q;i++)
{
m=0;ct=0;
cin>>size; cin>>ws; for(int j=1;j<=size;j++)
{
cin>>arr[j];
}
if(ws==1)
{
for(int j=1;j<=size;j++)
{
cout<<arr[j]<<" ";
}
}
else
{
for(int k=1;k<=ws;k++)
{
if(arr[k]>=m)
{
m=arr[k];
idx=k;
}
}
cout<<m<<" ";
for(int k=2,j;k<=(size-(ws-1));k++)
{
j=(k+(ws-1));
maxinwindow(arr,k,j);
cout<<m<<" ";
}
cout<<endl;
}
}
}