Sliding Window Maximum (Maximum of all subarrays of size K)
Last Updated :
23 Sep, 2024
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}, K = 3
Output: 3 3 4 5
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
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
Input: arr[] = {20, 10, 30}, K = 1
Output: 20 10 30
Using Nested Loops O(n * k) Time and O(1) Space
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.
Below is the implementation of the above approach:
C++
#include <iostream>
#include <vector>
using namespace std;
// Method to find the maximum for each
// and every contiguous subarray of size k.
vector<int> getKMax(const vector<int>& arr, int n, int k)
{
vector<int> res;
for (int i = 0; i <= n - k; i++) {
// Find maximum of subarray beginning
// with arr[i]
int max = arr[i];
for (int j = 1; j < k; j++) {
if (arr[i + j] > max)
max = arr[i + j];
}
res.push_back(max);
}
return res;
}
// Driver's code
int main()
{
vector<int> arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int n = arr.size();
int k = 3;
vector<int> res = getKMax(arr, n, k);
for (int maxVal : res) {
cout << maxVal << " ";
}
return 0;
}
C
// 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
// 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);
}
}
Python
# 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)
=
C#
// 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);
}
}
Javascript
// 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];
}
console.log( 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);
PHP
<?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);
?>
Time Complexity: O(n * k)
Auxiliary Space: O(1)
Using Max-Heap (n Log n) Time and O(N) Space
We use a priority queue or heap data structure. We make sure that heap has largest item of the current window.
- Create a max heap of the first k items
- Now slide the window one by one. While the next item to be added is greater than the heap top, remove the top. We mainly make sure that the greater items of the previous window are not there in a heap.
Below is the implementation of the above approach:
C++
#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;
vector<int> result = maxSlidingWindow(arr, k);
for (auto i : result)
cout << i << " ";
return 0;
}
Java
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 + " ");
}
}
}
Python
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=" ")
C#
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();
}
}
Javascript
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 + " ");
}
Time Complexity: O(n log n), 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
Using Set O(n Log n) Time and O(k) Space
To reduce the auxilary space to O(k), Set Data Structure can be used which allows deletion of any element in O(log 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.
Step-by-Step Algorithm:
- Create a Set to store and find the maximum element.
- Traverse through the array from start to end.
- Insert the element in theSet.
- If the loop counter is greater than or equal to k then delete the i-Kth element from the Set.
- Print the maximum element of the Set.
Below is the implementation of the above approach:
C++
#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;
vector<int> res = maxSlidingWindow(arr, k);
for (auto i : res)
cout << i << " ";
return 0;
}
Java
import java.util.*;
public class SlidingWindowMaximum {
// Function to find the maximum element in each sliding
// window of size k
public static List<Integer> maxSlidingWindow(int[] arr, int k) {
List<Integer> ans = new ArrayList<>();
TreeMap<Integer, Integer> treeMap = new TreeMap<>(Collections.reverseOrder());
// Initialize the TreeMap with the first k elements
for (int i = 0; i < k; i++) {
treeMap.put(arr[i], i);
}
// The maximum element in the first window
ans.add(treeMap.firstKey());
// Process the remaining elements
for (int i = k; i < arr.length; i++) {
// Add the current element to the TreeMap
treeMap.put(arr[i], i);
// Remove the (i-k)th element from the window
treeMap.remove(arr[i - k]);
// The maximum element in the current window
ans.add(treeMap.firstKey());
}
return ans;
}
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 i : result) {
System.out.print(i + " ");
}
}
}
Python
from sortedcontainers import SortedList
def maxSlidingWindow(arr, k):
ans = []
window = SortedList()
# Initialize the window with the first k elements
for i in range(k):
window.add((-arr[i], i)) # Use negative value for max-heap behavior
# The maximum element in the first window
ans.append(-window[0][0])
# Process the remaining elements
for i in range(k, len(arr)):
window.add((-arr[i], i))
# Remove the element that is out of the window
if i - k >= 0:
window.remove((-arr[i - k], i - k))
# The maximum element in the current window
ans.append(-window[0][0])
return ans
# Example usage:
arr = [2, 3, 7, 9, 5, 1, 6, 4, 3]
k = 3
result = maxSlidingWindow(arr, k)
print(result)
C#
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 + " "); }
}
}
Javascript
function maxSlidingWindow(arr, k)
{
let ans = [];
let window = [];
let maxSet = new Set();
// Initialize the sliding window and the maxSet with the
// first k elements
for (let i = 0; i < k; i++) {
window.push(arr[i]);
maxSet.add(arr[i]);
}
// The maximum element in the first window
ans.push(Math.max(...window));
// Process the remaining elements
for (let i = k; i < arr.length; i++) {
// Add the current element to the sliding window
window.push(arr[i]);
// Remove the oldest element from the sliding window
if (window.length > k) {
let removed = window.shift();
if (!window.includes(removed)) {
maxSet.delete(removed);
}
}
// Add the current element to the maxSet
maxSet.add(arr[i]);
// Get the maximum element in the current window
// from maxSet
ans.push(Math.max(...maxSet));
}
return ans;
}
// Example usage:
let arr = [ 2, 3, 7, 9, 5, 1, 6, 4, 3 ];
let k = 3;
let result = maxSlidingWindow(arr, k);
console.log(result);
Time Complexity: O(N log N), Where N is the size of the array.
Auxiliary Space: O(K), since size of set does not never exceeds K.
Using Deque O(n) Time and O(k) Space
Create a Deque, dq 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 dq to contain useful elements of current window and these useful elements are maintained in sorted order. The element at front of the dq is the largest and element at rear/back of dq is the smallest of current window.
Below is the illustration of the above approach:
Step-by-Step Algorithm:
- Create a deque to store only useful elements of current window.
- Run a loop and insert the first k elements in the deque. Before inserting the element, check if the element at the back of the queue is smaller than the current element, if it is so remove the element from the back of the deque until all elements left in the deque are greater than the current element. Then insert the current element, at the back of the deque.
- Now, run a loop from k to the end of the array.
- Print the front element of the deque.
- Remove the element from the front of the queue if they are out of the current window.
- Insert the next element in the deque. Before inserting the element, check if the element at the back of the queue is smaller than the current element, if it is so remove the element from the back of the deque until all elements left in the deque are greater than the current element. Then insert the current element, at the back of the deque.
- Print the maximum element of the last window.
Below is the implementation of the above approach:
C++
#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(const vector<int>& a, 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., a[Qi.front[]] to a[Qi.rear()] are sorted in
// decreasing order
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() && a[i] >= a[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 a[k] to a[n-1]
for (; i < a.size(); ++i) {
// The element at the front of the queue is the largest
// element of previous window, so print it
cout << a[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() && a[i] >= a[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 << a[Qi.front()];
}
// Driver's code
int main() {
vector<int> a = {12, 1, 78, 90, 57, 89, 56};
int k = 3;
// Function call
printKMax(a, k);
return 0;
}
Java
// 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);
}
}
Python
# 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)
C#
// 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);
}
}
Javascript
// 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);
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.