-
Notifications
You must be signed in to change notification settings - Fork 3
/
Maximum of all subarrays of size k.cpp
83 lines (77 loc) · 1.71 KB
/
Maximum of all subarrays of size k.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
/*
Given an array A and an integer K. Find the maximum for each and every contiguous subarray of size K.
Input:
The first line of input contains an integer T denoting the number of test cases. The first line of each test case contains
\a single integer N denoting the size of array and the size of subarray K. The second line contains N space-separated
integers A1, A2, ..., AN denoting the elements of the array.
Output:
Print the maximum for every subarray of size k.
Example:
Input:
2
9 3
1 2 3 1 4 5 2 3 6
10 4
8 5 10 7 9 4 15 12 90 13
Output:
3 3 4 5 5 5 6
10 10 10 15 15 90 90
Explanation:
Testcase 1: Starting from first subarray of size k = 3, we have 3 as maximum. Moving the window forward, maximum element
are as 3, 4, 5, 5, 5 and 6.
*/
using namespace std;
int main() {
//code
int t,n,*a,k,i,max,j,index;
cin>>t;
while(t--)
{
cin>>n;
cin>>k;
max=-1;
a=new int[n];
for(i=0;i<n;i++)
{
cin>>a[i];
}
max=a[0];
index=0;
for(i=1;i<k;i++)
{
if(a[i]>max)
{
max=a[i];
index=i;
}
}
cout<<max<<" ";
for(i=1;i<=n-k;i++)
{
if(index>=i)
{
if(a[i+k-1]>max)
{
max=a[i+k-1];
index=i+k-1;
}
cout<<max<<" ";
continue;
}
max=a[i];
index=i;
for(j=i+1;j<i+k;j++)
{
if(a[j]>max)
{
max=a[j];
index=j;
}
}
cout<<max<<" ";
}
cout<<endl;
delete []a;
}
return 0;
}