VOOZH about

URL: https://www.geeksforgeeks.org/dsa/sliding-window-maximum-set-2/

⇱ Sliding Window Maximum : Set 2 - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Sliding Window Maximum : Set 2

Last Updated : 12 Jul, 2025

Set 1: Sliding Window Maximum (Maximum of all subarrays of size k).
Given an array arr of size N and an integer K, the task is to find the maximum for each and every contiguous subarray of size K.


Examples: 

Input: arr[] = {1, 2, 3, 1, 4, 5, 2, 3, 6}, K = 3 
Output: 3 3 4 5 5 5 6 
All contiguous subarrays of size k are 
{1, 2, 3} => 3 
{2, 3, 1} => 3 
{3, 1, 4} => 4 
{1, 4, 5} => 5 
{4, 5, 2} => 5 
{5, 2, 3} => 5 
{2, 3, 6} => 6


Input: arr[] = {8, 5, 10, 7, 9, 4, 15, 12, 90, 13}, K = 4 
Output: 10 10 10 15 15 90 90  

Approach: To solve this in lesser space complexity we can use two pointer technique.  

  • The first variable pointer iterates through the subarray and finds the maximum element of a given size K
  • The second variable pointer marks the ending index of the first variable pointer i.e., (i + K - 1)th index.
  • When the first variable pointer reaches the index of the second variable pointer, the maximum of that subarray has been computed and will be printed.
  • The process is repeated until the second variable pointer reaches the last array index (i.e array_size - 1).


Below is the implementation of the above approach: 


Output
3 4 5 6 7 8 9 10 

Time Complexity: O(N*k) 
Auxiliary Space Complexity: O(1)
 

Using Dynamic Programming:

  • Firstly, divide the entire array into blocks of k elements such that each block contains k elements of the array(not always for the last block).
  • Maintain two dp arrays namely, left and right.
  • left[i] is the maximum of all elements that are to the left of current element(including current element) in the current block(block in which current element is present).
  • Similarly, right[i] is the maximum of all elements that are to the right of current element(including current element) in the current block(block in which current element is present).
  • Finally, when calculating the maximum element in any subarray of length k, we calculate the maximum of right[l] and left[r]
    where l = starting index of current sub array, r = ending index of current sub array

Below is the implementation of above approach,


Output
3 4 5 6 7 8 9 10 

Time Complexity : O(n)
Auxiliary Space    : O(n)

Comment