BackhardSliding Window Meta

Sliding Window Maximum Solution

Problem Statement

Given an array of integers and an integer k, find the maximum element in each window of size k.

Example 1
Input
[1, 3, -1, -3, 5, 7, 8, 12]
Output
[3, 5, 7]

Explanation: Step-by-step: with input [1, 3, -1, -3, 5, 7, 8, 12], we initialize a deque to store indices of the maximum elements in the current window. We iterate through the array, and for each element, we remove the indices of elements that are out of the current window from the deque. We then add the index of the current element to the deque and update the maximum element in the current window. We append the maximum element in the current window to the result array. Finally, we return the result array.

Example 2
Input
[5, 7, 8, 12, 15]
Output
[7]

Explanation: Step-by-step: with input [5, 7, 8, 12, 15], we initialize a deque to store indices of the maximum elements in the current window. We iterate through the array, and for each element, we remove the indices of elements that are out of the current window from the deque. We then add the index of the current element to the deque and update the maximum element in the current window. We append the maximum element in the current window to the result array. Finally, we return the result array.

Constraints

  • 1 <= n <= 10^5
  • 1 <= k <= n
  • -10^4 <= arr[i] <= 10^4
Live Compiler
Loading...
Test Cases & Output
🔒 Sign up to run your code

🚀 Practice this problem

Run code, get AI hints & track streak

Sign Up Free