Sliding Maximum

You are given an array 'ARR' of integers of length 'N' and a positive integer 'K'. You need to find the maximum elements for each and every contiguous subarray of size K of the array.

For example
'ARR' =  [3, 4, -1, 1, 5] and 'K' = 3
Output =  [4, 4, 5]

Since the maximum element of the first subarray of length three ([3, 4, -1]) is 4, the maximum element of the second subarray of length three ([4, -1, 1]) is also 4 and the maximum element of the last subarray of length three ([-1, 1, 5]) is 5, so you need to return [4, 4, 5]. 
Input format:
The first line of input contains a single integer 'T', representing the number of test cases or queries to be run. Then the 'T' test cases follow.

The first line of each test case contains two positive integers 'N' and 'K' which represent the length of the array and length of the subarray respectively.

The Second line of each test case contains 'N' space-separated integers representing the elements of the array.
Output Format :
For each test case, print 'X' space-separated integer denoting maximum elements for each and every contiguous subarray of size 'K' of the array. Where 'X' is the number of subarray of size 'K' in array 'arr'.

Output for each test case will be printed in a separate line.
Note:
You do not need to print anything; it has already been taken care of. Just implement the given function.
Constraint :
1 <= T <= 10
1 <= N <= 10^5
-10^5 <= arr[i] <= 10^5
1 <= K <= N

Time Limit: 1 sec
CodingNinjas
author
2y

It was a standard problem so I know the exact solution, you can simply use dequeue + two pointers to solve this questions.

CodingNinjas
author
2y
Brute Force
  1. We know that an array of size ‘N’ will have in total ‘N’ - ‘K’ - 1 subarray of size ‘K'.
  2. Thus, what a trivial solution suggests is that we traverse over all subarrays of size ‘K', and calcul...read more
CodingNinjas
author
2y
MaxHeap
  1. Create a class pair where we will have two variables i.e elements of the given array and their corresponding indexes.
  2. Create an array and of size ‘N’ - ‘K’ + 1 size to store the maximum element ...read more
CodingNinjas
author
2y
Dequeue

The idea is to use the deque to hold the index of the maximum element and restrict the deque size to ‘K’. We can use a double-ended queue to keep only the indices of those elements which are us...read more

Add answer anonymously...
CommVault Software Developer Intern Interview Questions
Stay ahead in your career. Get AmbitionBox app
qr-code
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+

Reviews

4 L+

Interviews

4 Cr+

Salaries

1 Cr+

Users/Month

Contribute to help millions
Get AmbitionBox app

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2024 Info Edge (India) Ltd.

Follow us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter