Find Max Element in Window
EasyPractice library · +10 XPsliding windowarraysmaximum
Given an array of N integers and an integer K, find the maximum element in each contiguous subarray of size K. The window slides from left to right, one position at a time.
Input
The first line contains two integers N and K, separated by a space. The second line contains N integers, the elements of the array.
Output
Print N-K+1 integers, separated by spaces. Each integer is the maximum element of a sliding window of size K.
Constraints
1 <= K <= N <= 1000. The elements of the array are integers between -10^9 and 10^9.
Time limit 1 s (native code; slower languages get more)Memory 256 MB15 hidden tests
Example 1
Input
5 3 1 3 2 4 5
Output
3 4 5
The windows are [1, 3, 2], [3, 2, 4], [2, 4, 5]. Their maximums are 3, 4, 5.
Example 2
Input
7 2 10 5 2 7 8 7 3
Output
10 5 7 8 8 7
The windows are [10, 5], [5, 2], [2, 7], [7, 8], [8, 7], [7, 3]. Their maximums are 10, 5, 7, 8, 8, 7.
Hints
# Read the input from stdin and print the answer.
import sys
def main():
data = sys.stdin.read().split()
# your code here
main()
Example 1 input
5 3 1 3 2 4 5
Example 2 input
7 2 10 5 2 7 8 7 3