Given an array A and an integer K. Find the maximum for each and every contiguous subarray of size K. |
Given an array A and an integer K. Find the maximum for each and every contiguous 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
#include <bits/stdc++.h>using namespace std;int main() {//codeint t;cin >> t;while (t--) {int n, m;cin >> n >> m;int a[n];for (int i = 0; i < n; ++i) {cin >> a[i];}int k = m, mx = 0, ind = -1;for (int i = 0; i < m; ++i) {if (mx < a[i]) {mx = a[i];ind = i;}}while (k <= n) {cout << mx << " ";if (a[k] > mx && k - ind < m)mx = a[k], ind = k;else if (k - ind == m) {mx = 0;for (int i = ind + 1; i <= k; ++i)if (mx < a[i]) {mx = a[i];ind = i;}}++k;}cout << endl;}return 0;}