Open In App

Sliding Window Maximum (Maximum of all subarrays of size K)

Given an array and an integer K, 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
Explanation: Maximum of 1, 2, 3 is 3
                       Maximum of 2, 3, 1 is 3
                       Maximum of 3, 1, 4 is 4
                       Maximum of 1, 4, 5 is 5
                       Maximum of 4, 5, 2 is 5 
                       Maximum of 5, 2, 3 is 5
                       Maximum of 2, 3, 6 is 6

Input: arr[] = {8, 5, 10, 7, 9, 4, 15, 12, 90, 13}, K = 4 
Output: 10 10 10 15 15 90 90          
Explanation: Maximum of first 4 elements is 10, similarly for next 4 
                       elements (i.e from index 1 to 4) is 10, So the sequence 
                       generated is 10 10 10 15 15 90 90

Recommended Practice
 

Naive Approach:

The idea is very basic run a nested loop, the outer loop which will mark the starting point of the subarray of length K, the inner loop will run from the starting index to index+K, and print the maximum element among these K elements. 

Follow the given steps to solve the problem:

Below is the implementation of the above approach:




// C++ program for the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Method to find the maximum for each
// and every contiguous subarray of size K.
void printKMax(int arr[], int N, int K)
{
    int j, max;
 
    for (int i = 0; i <= N - K; i++) {
        max = arr[i];
 
        for (j = 1; j < K; j++) {
            if (arr[i + j] > max)
                max = arr[i + j];
        }
        cout << max << " ";
    }
}
 
// Driver's code
int main()
{
    int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
    int N = sizeof(arr) / sizeof(arr[0]);
    int K = 3;
   
      // Function call
    printKMax(arr, N, K);
    return 0;
}
 
// This code is contributed by rathbhupendra




// C program for the above approach
#include <stdio.h>
 
void printKMax(int arr[], int N, int K)
{
    int j, max;
 
    for (int i = 0; i <= N - K; i++) {
        max = arr[i];
 
        for (j = 1; j < K; j++) {
            if (arr[i + j] > max)
                max = arr[i + j];
        }
        printf("%d ", max);
    }
}
 
// Driver's Code
int main()
{
    int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
    int N = sizeof(arr) / sizeof(arr[0]);
    int K = 3;
   
      // Function call
    printKMax(arr, N, K);
    return 0;
}




// Java program for the above approach
 
public class GFG {
   
    // Method to find the maximum for
    // each and every contiguous
    // subarray of size K.
    static void printKMax(int arr[], int N, int K)
    {
        int j, max;
 
        for (int i = 0; i <= N - K; i++) {
 
            max = arr[i];
 
            for (j = 1; j < K; j++) {
                if (arr[i + j] > max)
                    max = arr[i + j];
            }
            System.out.print(max + " ");
        }
    }
 
    // Driver's code
    public static void main(String args[])
    {
        int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
        int K = 3;
       
          // Function call
        printKMax(arr, arr.length, K);
    }
}
 
// This code is contributed by Sumit Ghosh




// C# program for the above approach
 
using System;
 
class GFG {
   
    // Method to find the maximum for
    // each and every contiguous subarray
    // of size k.
    static void printKMax(int[] arr, int N, int K)
    {
        int j, max;
 
        for (int i = 0; i <= N - K; i++) {
 
            max = arr[i];
 
            for (j = 1; j < K; j++) {
                if (arr[i + j] > max)
                    max = arr[i + j];
            }
            Console.Write(max + " ");
        }
    }
 
    // Driver's code
    public static void Main()
    {
        int[] arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
        int K = 3;
        printKMax(arr, arr.Length, K);
    }
}
 
// This Code is Contributed by Sam007




// JavaScript Program to find the maximum for
// each and every contiguous subarray of size k.
 
// Method to find the maximum for each
// and every contiguous subarray of size k.
function printKMax(arr,n,k)
{
    let j, max;
 
    for (let i = 0; i <= n - k; i++)
    {
        max = arr[i];
 
        for (j = 1; j < k; j++)
        {
            if (arr[i + j] > max)
                max = arr[i + j];
        }
         document.write( max + " ");
    }
}
 
// Driver code
 
    let arr = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ];
    let n =arr.length;
    let k = 3;
    printKMax(arr, n, k);
 
// This code contributed by gauravrajput1




<?php
// php program for the above approach
 
function printKMax($arr, $N, $K)
{
    $j; $max;
 
    for ($i = 0; $i <= $N - $K; $i++)
    {
        $max = $arr[$i];
 
        for ($j = 1; $j < $K; $j++)
        {
            if ($arr[$i + $j] > $max)
            $max = $arr[$i + $j];
        }
        printf("%d ", $max);
    }
}
 
// Driver's Code
$arr = array(1, 2, 3, 4, 5,
             6, 7, 8, 9, 10);
$N = count($arr);
$K = 3;
 
// Function call
printKMax($arr, $N, $K);
 
// This Code is Contributed by anuj_67.
?>




# Python3 program for the above approach
 
# Method to find the maximum for each
# and every contiguous subarray
# of size K
 
def printMax(arr, N, K):
    max = 0
 
    for i in range(N - K + 1):
        max = arr[i]
        for j in range(1, K):
            if arr[i + j] > max:
                max = arr[i + j]
        print(str(max) + " ", end="")
 
 
# Driver's code
if __name__ == "__main__":
    arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    N = len(arr)
    K = 3
     
    # Function call
    printMax(arr, N, K)
 
# This code is contributed by Shiv Shankar

Output
3 4 5 6 7 8 9 10 








Time Complexity: O(N * K), The outer loop runs N-K+1 times and the inner loop runs K times for every iteration of the outer loop. So time complexity is O((n-k+1)*k) which can also be written as O(N * K)
Auxiliary Space: O(1)

Maximum of all subarrays of size K using Max-Heap: 

Below is the implementation of the above approach:




#include <bits/stdc++.h>
using namespace std;
 
// Function to find the maximum element in each sliding
// window of size k
vector<int> maxSlidingWindow(vector<int>& arr, int k)
{
    vector<int> ans;
    priority_queue<pair<int, int> > heap;
 
    // Initialize the heap with the first k elements
    for (int i = 0; i < k; i++)
        heap.push({ arr[i], i });
 
    // The maximum element in the first window
    ans.push_back(heap.top().first);
 
    // Process the remaining elements
    for (int i = k; i < arr.size(); i++) {
 
        // Add the current element to the heap
        heap.push({ arr[i], i });
 
        // Remove elements that are outside the current
        // window
        while (heap.top().second <= i - k)
            heap.pop();
 
        // The maximum element in the current window
        ans.push_back(heap.top().first);
    }
 
    return ans;
}
 
int main()
{
    vector<int> arr = { 2, 3, 7, 9, 5, 1, 6, 4, 3 };
    int k = 3;
 
    // Find the maximum element in each sliding window of
    // size k
    vector<int> result = maxSlidingWindow(arr, k);
 
    // Print the results
    for (auto i : result)
        cout << i << " ";
 
    return 0;
}




import java.util.ArrayList;
import java.util.List;
import java.util.PriorityQueue;
 
public class Main {
    public static List<Integer> maxSlidingWindow(int[] arr,
                                                 int k)
    {
        List<Integer> ans = new ArrayList<>();
        PriorityQueue<Pair> heap = new PriorityQueue<>(
            (a, b) -> b.value - a.value);
 
        // Initialize the heap with the first k elements
        for (int i = 0; i < k; i++) {
            heap.offer(new Pair(arr[i], i));
        }
 
        // The maximum element in the first window
        ans.add(heap.peek().value);
 
        // Process the remaining elements
        for (int i = k; i < arr.length; i++) {
            heap.offer(new Pair(arr[i], i));
 
            // Remove elements that are outside the current
            // window
            while (heap.peek().index <= i - k) {
                heap.poll();
            }
 
            // The maximum element in the current window
            ans.add(heap.peek().value);
        }
 
        return ans;
    }
 
    static class Pair {
        int value;
        int index;
 
        public Pair(int value, int index)
        {
            this.value = value;
            this.index = index;
        }
    }
 
    public static void main(String[] args)
    {
        int[] arr = { 2, 3, 7, 9, 5, 1, 6, 4, 3 };
        int k = 3;
 
        // Find the maximum element in each sliding window
        // of size k
        List<Integer> result = maxSlidingWindow(arr, k);
 
        // Print the results
        for (int num : result) {
            System.out.print(num + " ");
        }
    }
}




using System;
using System.Collections.Generic;
 
class GFG
{
    static List<int> MaxSlidingWindow(List<int> arr, int k)
    {
        List<int> ans = new List<int>();
        Queue<int> deque = new Queue<int>();
 
        for (int i = 0; i < arr.Count; i++)
        {
            // Remove elements that are outside the current window
          // from the front of the deque
            while (deque.Count > 0 && deque.Peek() < i - k + 1)
                deque.Dequeue();
 
            // Remove elements that are less than the current element
          // from the back of the deque
            while (deque.Count > 0 && arr[deque.Peek()] < arr[i])
                deque.Dequeue();
 
            // Add the current element's index to the back of the deque
            deque.Enqueue(i);
 
            // If the current index is equal to or greater than k - 1,
          // then we can start adding elements to the result list
            if (i >= k - 1)
                ans.Add(arr[deque.Peek()]);
        }
 
        return ans;
    }
 
    static void Main()
    {
        List<int> arr = new List<int> { 2, 3, 7, 9, 5, 1, 6, 4, 3 };
        int k = 3;
 
        // Find the maximum element in each sliding window of size k
        List<int> result = MaxSlidingWindow(arr, k);
 
        // Print the results
        foreach (int i in result)
            Console.Write(i + " ");
 
        Console.ReadLine();
    }
}




class Pair {
    constructor(value, index) {
        this.value = value;
        this.index = index;
    }
}
 
function maxSlidingWindow(arr, k) {
    const ans = [];
    const heap = [];
 
    // Initialize the heap with the first k elements
    for (let i = 0; i < k; i++) {
        heap.push(new Pair(arr[i], i));
    }
    heap.sort((a, b) => b.value - a.value);
 
    // The maximum element in the first window
    ans.push(heap[0].value);
 
    // Process the remaining elements
    for (let i = k; i < arr.length; i++) {
        heap.push(new Pair(arr[i], i));
 
        // Remove elements that are outside the current window
        while (heap[0].index <= i - k) {
            heap.shift();
        }
        heap.sort((a, b) => b.value - a.value);
 
        // The maximum element in the current window
        ans.push(heap[0].value);
    }
 
    return ans;
}
 
const arr = [2, 3, 7, 9, 5, 1, 6, 4, 3];
const k = 3;
 
// Find the maximum element in each sliding window of size k
const result = maxSlidingWindow(arr, k);
 
// Print the results
for (const num of result) {
    console.log(num + " ");
}




import heapq
 
 
def max_sliding_window(arr, k):
    ans = []
    heap = []
 
    # Initialize the heap with the first k elements
    for i in range(k):
        heapq.heappush(heap, (-arr[i], i))
 
    # The maximum element in the first window
    ans.append(-heap[0][0])
 
    # Process the remaining elements
    for i in range(k, len(arr)):
        heapq.heappush(heap, (-arr[i], i))
 
        # Remove elements that are outside the current window
        while heap[0][1] <= i - k:
            heapq.heappop(heap)
 
        # The maximum element in the current window
        ans.append(-heap[0][0])
 
    return ans
 
 
arr = [2, 3, 7, 9, 5, 1, 6, 4, 3]
k = 3
 
# Find the maximum element in each sliding window of size k
result = max_sliding_window(arr, k)
 
# Print the results
for num in result:
    print(num, end=" ")

Output
7 9 9 9 6 6 6 








Time Complexity: O(NlogN), Where N is the size of the array.
Auxiliary Space: O(N), where N is the size of the array, this method requires O(N) space in the worst case when the input array is an increasing array

Maximum of all subarrays of size K using Set:

To reduce the auxilary space to O(K), Set Data Structure can be used which allows deletion of any element in O(logn N) time. Thus the size of set will never exceed K, if we delete delete the (i-Kt)h element from the Set while traversing.

Follow the given steps to solve the problem:

  1. Create a Set to store and find the maximum element.
  2. Traverse through the array from start to end.
  3. Insert the element in theSet.
  4. If the loop counter is greater than or equal to k then delete the i-Kth element from the Set.
  5. Print the maximum element of the Set.

Below is the implementation of the above approach:




#include <bits/stdc++.h>
using namespace std;
 
// Function to find the maximum element in each sliding
// window of size k
vector<int> maxSlidingWindow(vector<int>& arr, int k)
{
    vector<int> ans;
    set<pair<int, int>, greater<pair<int,int>>> st;
 
    // Initialize the set with the first k elements
    for (int i = 0; i < k; i++)
        st.insert({ arr[i], i });
 
    // The maximum element in the first window
    ans.push_back((st.begin())->first);
 
    // Process the remaining elements
    for (int i = k; i < arr.size(); i++) {
 
        // Add the current element to the set
        st.insert({ arr[i], i });
 
        // Remove the (i-k)th element from the window
        st.erase({ arr[i - k], (i - k) });
 
        // The maximum element in the current window
        ans.push_back(st.begin()->first);
    }
 
    return ans;
}
 
int main()
{
    vector<int> arr = { 2, 3, 7, 9, 5, 1, 6, 4, 3 };
    int k = 3;
 
    // Find the maximum element in each sliding window of
    // size k
    vector<int> result = maxSlidingWindow(arr, k);
 
    // Print the results
    for (auto i : result)
        cout << i << " ";
 
    return 0;
}




import java.util.ArrayDeque;
import java.util.Deque;
 
public class MaxSlidingWindow {
    // Function to find the maximum element in each sliding
    // window of size k
    static int[] maxSlidingWindow(int[] arr, int k)
    {
        int n = arr.length;
        int[] ans = new int[n - k + 1];
        Deque<Integer> maxInWindow = new ArrayDeque<>();
 
        // Initialize maxInWindow with the first k elements
        for (int i = 0; i < k; i++) {
            while (!maxInWindow.isEmpty()
                   && arr[i]
                          >= arr[maxInWindow.peekLast()]) {
                maxInWindow.removeLast();
            }
            maxInWindow.addLast(i);
        }
 
        // The maximum element in the first window
        ans[0] = arr[maxInWindow.peekFirst()];
 
        // Process the remaining elements
        for (int i = k; i < n; i++) {
            // Remove elements that are out of the current
            // window
            while (!maxInWindow.isEmpty()
                   && maxInWindow.peekFirst() <= i - k) {
                maxInWindow.removeFirst();
            }
 
            // Remove elements that are not needed in the
            // current window
            while (!maxInWindow.isEmpty()
                   && arr[i]
                          >= arr[maxInWindow.peekLast()]) {
                maxInWindow.removeLast();
            }
 
            maxInWindow.addLast(i);
            ans[i - k + 1] = arr[maxInWindow.peekFirst()];
        }
 
        return ans;
    }
 
    // Driver program
    public static void main(String[] args)
    {
        int[] arr = { 2, 3, 7, 9, 5, 1, 6, 4, 3 };
        int k = 3;
 
        // Find the maximum element in each sliding window
        // of size k
        int[] result = maxSlidingWindow(arr, k);
 
        // Print the results
        System.out.print(
            "Maximum elements in each sliding window: ");
        for (int i : result)
            System.out.print(i + " ");
    }
}




from collections import deque
 
# Function to find the maximum element in each sliding window of size k
 
 
def maxSlidingWindow(arr, k):
    ans = []
    deq = deque()
 
    # Initialize the deque with the first k elements
    for i in range(k):
        while deq and arr[i] >= arr[deq[-1]]:
            deq.pop()
        deq.append(i)
 
    # The maximum element in the first window
    ans.append(arr[deq[0]])
 
    # Process the remaining elements
    for i in range(k, len(arr)):
        # Remove elements that are out of the current window
        while deq and deq[0] <= i - k:
            deq.popleft()
 
        # Remove elements that are less than the current element
        while deq and arr[i] >= arr[deq[-1]]:
            deq.pop()
 
        deq.append(i)
 
        # The maximum element in the current window
        ans.append(arr[deq[0]])
 
    return ans
 
 
# Main function
if __name__ == "__main__":
    arr = [2, 3, 7, 9, 5, 1, 6, 4, 3]
    k = 3
 
    # Find the maximum element in each sliding window of size k
    result = maxSlidingWindow(arr, k)
 
    # Print the results
    print(result)




using System;
using System.Collections.Generic;
 
class Program {
    // Function to find the maximum element in each sliding
    // window of size k
    static List<int> MaxSlidingWindow(List<int> arr, int k)
    {
        List<int> ans = new List<int>();
        List<int> maxInWindow = new List<int>();
 
        // Initialize maxInWindow with the first k elements
        for (int i = 0; i < k; i++) {
            while (
                maxInWindow.Count > 0
                && arr[i]
                       >= arr[maxInWindow[maxInWindow.Count
                                          - 1]]) {
                maxInWindow.RemoveAt(maxInWindow.Count - 1);
            }
            maxInWindow.Add(i);
        }
 
        // The maximum element in the first window
        ans.Add(arr[maxInWindow[0]]);
 
        // Process the remaining elements
        for (int i = k; i < arr.Count; i++) {
            // Remove elements that are out of the current
            // window
            while (maxInWindow.Count > 0
                   && maxInWindow[0] <= i - k) {
                maxInWindow.RemoveAt(0);
            }
 
            // Remove elements that are not needed in the
            // current window
            while (
                maxInWindow.Count > 0
                && arr[i]
                       >= arr[maxInWindow[maxInWindow.Count
                                          - 1]]) {
                maxInWindow.RemoveAt(maxInWindow.Count - 1);
            }
 
            maxInWindow.Add(i);
            ans.Add(arr[maxInWindow[0]]);
        }
 
        return ans;
    }
 
    static void Main(string[] args)
    {
        List<int> arr
            = new List<int>{ 2, 3, 7, 9, 5, 1, 6, 4, 3 };
        int k = 3;
 
        List<int> result = MaxSlidingWindow(arr, k);
 
        Console.WriteLine(
            "Maximum elements in each sliding window:");
        foreach(int i in result) { Console.Write(i + " "); }
    }
}




function maxSlidingWindow(arr, k) {
    const ans = [];
    const maxInWindow = [];
 
    // Initialize maxInWindow with the first k elements
    for (let i = 0; i < k; i++) {
        while (maxInWindow.length > 0 && arr[i] >= arr[maxInWindow[maxInWindow.length - 1]]) {
            maxInWindow.pop();
        }
        maxInWindow.push(i);
    }
 
    // The maximum element in the first window
    ans.push(arr[maxInWindow[0]]);
 
    // Process the remaining elements
    for (let i = k; i < arr.length; i++) {
        // Remove elements that are out of the current window
        while (maxInWindow.length > 0 && maxInWindow[0] <= i - k) {
            maxInWindow.shift();
        }
 
        // Remove elements that are not needed in the current window
        while (maxInWindow.length > 0 && arr[i] >= arr[maxInWindow[maxInWindow.length - 1]]) {
            maxInWindow.pop();
        }
 
        maxInWindow.push(i);
        ans.push(arr[maxInWindow[0]]);
    }
 
    return ans;
}
 
const arr = [2, 3, 7, 9, 5, 1, 6, 4, 3];
const k = 3;
 
const result = maxSlidingWindow(arr, k);
 
console.log("Maximum elements in each sliding window: " + result.join(' '));

Output
7 9 9 9 6 6 6 








Time Complexity: O(NlogN), Where N is the size of the array.
Auxiliary Space: O(K), since size of set does not never exceeds K.

Maximum of all subarrays of size K using Deque: 

Create a Deque, Qi of capacity K, that stores only useful elements of current window of K elements. An element is useful if it is in current window and is greater than all other elements on right side of it in current window. Process all array elements one by one and maintain Qi to contain useful elements of current window and these useful elements are maintained in sorted order. The element at front of the Qi is the largest and element at rear/back of Qi is the smallest of current window.

Below is the dry run of the above approach: 

Follow the given steps to solve the problem:

Below is the implementation of the above approach:




// CPP program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// A Dequeue (Double ended queue) based
// method for printing maximum element of
// all subarrays of size k
void printKMax(int arr[], int N, int K)
{
 
    // Create a Double Ended Queue,
    // Qi that will store indexes
    // of array elements
    // The queue will store indexes
    // of useful elements in every
    // window and it will
    // maintain decreasing order of
    // values from front to rear in Qi, i.e.,
    // arr[Qi.front[]] to arr[Qi.rear()]
    // are sorted in decreasing order
    std::deque<int> Qi(K);
 
    /* Process first k (or first window)
     elements of array */
    int i;
    for (i = 0; i < K; ++i) {
 
        // For every element, the previous
        // smaller elements are useless so
        // remove them from Qi
        while ((!Qi.empty()) && arr[i] >= arr[Qi.back()])
 
            // Remove from rear
            Qi.pop_back();
 
        // Add new element at rear of queue
        Qi.push_back(i);
    }
 
    // Process rest of the elements,
    // i.e., from arr[k] to arr[n-1]
    for (; i < N; ++i) {
 
        // The element at the front of
        // the queue is the largest element of
        // previous window, so print it
        cout << arr[Qi.front()] << " ";
 
        // Remove the elements which
        // are out of this window
        while ((!Qi.empty()) && Qi.front() <= i - K)
 
            // Remove from front of queue
            Qi.pop_front();
 
        // Remove all elements
        // smaller than the currently
        // being added element (remove
        // useless elements)
        while ((!Qi.empty()) && arr[i] >= arr[Qi.back()])
            Qi.pop_back();
 
        // Add current element at the rear of Qi
        Qi.push_back(i);
    }
 
    // Print the maximum element
    // of last window
    cout << arr[Qi.front()];
}
 
// Driver's code
int main()
{
    int arr[] = { 12, 1, 78, 90, 57, 89, 56 };
    int N = sizeof(arr) / sizeof(arr[0]);
    int K = 3;
 
    // Function call
    printKMax(arr, N, K);
    return 0;
}




// Java Program to find the maximum for
// each and every contiguous subarray of size K.
import java.util.Deque;
import java.util.LinkedList;
 
public class SlidingWindow {
 
    // A Dequeue (Double ended queue)
    // based method for printing
    // maximum element of
    // all subarrays of size K
    static void printMax(int arr[], int N, int K)
    {
 
        // Create a Double Ended Queue, Qi
        // that will store indexes of array elements
        // The queue will store indexes of
        // useful elements in every window and it will
        // maintain decreasing order of values
        // from front to rear in Qi, i.e.,
        // arr[Qi.front[]] to arr[Qi.rear()]
        // are sorted in decreasing order
        Deque<Integer> Qi = new LinkedList<Integer>();
 
        /* Process first k (or first window)
        elements of array */
        int i;
        for (i = 0; i < K; ++i) {
 
            // For every element, the previous
            // smaller elements are useless so
            // remove them from Qi
            while (!Qi.isEmpty()
                   && arr[i] >= arr[Qi.peekLast()])
 
                // Remove from rear
                Qi.removeLast();
 
            // Add new element at rear of queue
            Qi.addLast(i);
        }
 
        // Process rest of the elements,
        // i.e., from arr[k] to arr[n-1]
        for (; i < N; ++i) {
 
            // The element at the front of the
            // queue is the largest element of
            // previous window, so print it
            System.out.print(arr[Qi.peek()] + " ");
 
            // Remove the elements which
            // are out of this window
            while ((!Qi.isEmpty()) && Qi.peek() <= i - K)
                Qi.removeFirst();
 
            // Remove all elements smaller
            // than the currently
            // being added element (remove
            // useless elements)
            while ((!Qi.isEmpty())
                   && arr[i] >= arr[Qi.peekLast()])
                Qi.removeLast();
 
            // Add current element at the rear of Qi
            Qi.addLast(i);
        }
 
        // Print the maximum element of last window
        System.out.print(arr[Qi.peek()]);
    }
 
    // Driver's code
    public static void main(String[] args)
    {
        int arr[] = { 12, 1, 78, 90, 57, 89, 56 };
        int K = 3;
       
          // Function call
        printMax(arr, arr.length, K);
    }
}
// This code is contributed by Sumit Ghosh




// C# Program to find the maximum for each
// and every contiguous subarray of size K.
 
using System;
using System.Collections.Generic;
 
public class SlidingWindow {
 
    // A Dequeue (Double ended queue) based
    // method for printing maximum element of
    // all subarrays of size K
    static void printMax(int[] arr, int N, int K)
    {
 
        // Create a Double Ended Queue, Qi that
        // will store indexes of array elements
        // The queue will store indexes of useful
        // elements in every window and it will
        // maintain decreasing order of values
        // from front to rear in Qi, i.e.,
        // arr[Qi.front[]] to arr[Qi.rear()]
        // are sorted in decreasing order
        List<int> Qi = new List<int>();
 
        /* Process first K (or first window)
        elements of array */
        int i;
        for (i = 0; i < K; ++i) {
            // For every element, the previous
            // smaller elements are useless so
            // remove them from Qi
            while (Qi.Count != 0
                   && arr[i] >= arr[Qi[Qi.Count - 1]])
 
                // Remove from rear
                Qi.RemoveAt(Qi.Count - 1);
 
            // Add new element at rear of queue
            Qi.Insert(Qi.Count, i);
        }
 
        // Process rest of the elements,
        // i.e., from arr[k] to arr[n-1]
        for (; i < N; ++i) {
            // The element at the front of
            // the queue is the largest element of
            // previous window, so print it
            Console.Write(arr[Qi[0]] + " ");
 
            // Remove the elements which are
            // out of this window
            while ((Qi.Count != 0) && Qi[0] <= i - K)
                Qi.RemoveAt(0);
 
            // Remove all elements smaller
            // than the currently
            // being added element (remove
            // useless elements)
            while ((Qi.Count != 0)
                   && arr[i] >= arr[Qi[Qi.Count - 1]])
                Qi.RemoveAt(Qi.Count - 1);
 
            // Add current element at the rear of Qi
            Qi.Insert(Qi.Count, i);
        }
 
        // Print the maximum element of last window
        Console.Write(arr[Qi[0]]);
    }
 
    // Driver's code
    public static void Main(String[] args)
    {
        int[] arr = { 12, 1, 78, 90, 57, 89, 56 };
        int K = 3;
       
          // Function call
        printMax(arr, arr.Length, K);
    }
}
 
// This code has been contributed by 29AjayKumar




// We have used array in javascript to implement methods of dequeue
// A Dequeue (Double ended queue) based
// method for printing maximum element of
// all subarrays of size k
function printKMax(arr,n,k)
{
    // creating string str to be printed at last
    let str ="";
     
    // Create a Double Ended Queue,
    // Qi that will store indexes
    // of array elements
    // The queue will store indexes
    // of useful elements in every
    // window and it will
    // maintain decreasing order of
    // values from front to rear in Qi, i.e.,
    // arr[Qi.front[]] to arr[Qi.rear()]
    // are sorted in decreasing order
    // std::deque<int> Qi(k);
    let Qi = [];
 
    /* Process first k (or first window)
     elements of array */
    let i;
    for (i = 0; i < k; ++i)
    {
     
        // For every element, the previous
        // smaller elements are useless so
        // remove them from Qi
        while ((Qi.length!=0) && arr[i] >=
                            arr[Qi[Qi.length-1]])
           
             // Remove from rear
            Qi.pop();
 
        // Add new element at rear of queue
        Qi.push(i);
    }
 
    // Process rest of the elements,
    // i.e., from arr[k] to arr[n-1]
    for (i; i < n; ++i)
    {
     
        // The element at the front of
        // the queue is the largest element of
        // previous window, so print it
        str+=arr[Qi[0]] + " ";
        // console.log(arr[Qi[0]] + " ") ;
 
        // Remove the elements which
        // are out of this window
        while ((Qi.length!=0) && Qi[0] <= i - k)
           
            // Remove from front of queue
            Qi.shift();
 
        // Remove all elements
        // smaller than the currently
        // being added element (remove
        // useless elements)
        while ((Qi.length!=0) && arr[i] >= arr[Qi[Qi.length-1]])
            Qi.pop();
 
        // Add current element at the rear of Qi
        Qi.push(i);
    }
 
    // Print the maximum element
    // of last window
    str += arr[Qi[0]];
    console.log(str);
}
 
let arr = [ 12, 1, 78, 90, 57, 89, 56 ];
let n = arr.length;
let k = 3;
printKMax(arr, n, k);
 
// This code is contributed by akashish__




# Python3 program to find the maximum for
# each and every contiguous subarray of
# size K
 
from collections import deque
 
# A Deque (Double ended queue) based
# method for printing maximum element
# of all subarrays of size K
 
 
def printMax(arr, N, K):
    """ Create a Double Ended Queue, Qi that
    will store indexes of array elements.
    The queue will store indexes of useful
    elements in every window and it will
    maintain decreasing order of values from
    front to rear in Qi, i.e., arr[Qi.front[]]
    to arr[Qi.rear()] are sorted in decreasing
    order"""
    Qi = deque()
 
    # Process first k (or first window)
    # elements of array
    for i in range(K):
 
        # For every element, the previous
        # smaller elements are useless
        # so remove them from Qi
        while Qi and arr[i] >= arr[Qi[-1]]:
            Qi.pop()
 
        # Add new element at rear of queue
        Qi.append(i)
 
    # Process rest of the elements, i.e.
    # from arr[k] to arr[n-1]
    for i in range(K, N):
 
        # The element at the front of the
        # queue is the largest element of
        # previous window, so print it
        print(str(arr[Qi[0]]) + " ", end="")
 
        # Remove the elements which are
        # out of this window
        while Qi and Qi[0] <= i-K:
 
            # remove from front of deque
            Qi.popleft()
 
        # Remove all elements smaller than
        # the currently being added element
        # (Remove useless elements)
        while Qi and arr[i] >= arr[Qi[-1]]:
            Qi.pop()
 
        # Add current element at the rear of Qi
        Qi.append(i)
 
    # Print the maximum element of last window
    print(str(arr[Qi[0]]))
 
 
# Driver's code
if __name__ == "__main__":
    arr = [12, 1, 78, 90, 57, 89, 56]
    K = 3
     
    # Function call
    printMax(arr, len(arr), K)
 
# This code is contributed by Shiv Shankar

Output
78 90 90 90 89








Time Complexity: O(N). It seems more than O(N) at first look. It can be observed that every element of the array is added and removed at most once. So there are a total of 2n operations.
Auxiliary Space: O(K). Elements stored in the dequeue take O(K) space.

Below is an extension of this problem: 
Sum of minimum and maximum elements of all subarrays of size k.


Article Tags :