880227. Maximum Of All Subarrays Of Size K Using Dequeue

Medium

Maximum Of All Subarrays Of Size K Using Dequeue

Summary

The problem is to find the maximum element in all subarrays of size K from a given array. This problem involves using a dequeue data structure, which is used to efficiently keep track of the maximum elements in the sliding window.

Detailed Explanation

To solve this problem, we can use a dequeue to store the indices of the elements in the current window. We start by initializing the dequeue with the first K elements and their corresponding maximum value. Then, for each subsequent element, we remove the smallest element from the left side of the dequeue (since it's out of the current window) and add the new element along with its maximum value to the right side of the dequeue.

Here is a step-by-step breakdown of the solution:

  1. Initialize an empty dequeue.
  2. For each element in the array, do the following:
    • If the dequeue is not full (i.e., it has less than K elements), add the new element and its maximum value to the right side of the dequeue.
    • If the dequeue is full, remove the smallest element from the left side of the dequeue (since it's out of the current window).
  3. As we iterate through the array, at each step, keep track of the maximum element in the current window by looking at the maximum value stored in the front of the dequeue.
  4. Finally, print or store the maximum elements for all subarrays of size K.

Time complexity: O(n), where n is the number of elements in the array. This is because we are scanning through the array once and each operation on the dequeue takes constant time.

Space complexity: O(K), where K is the window size. This is because we need to store at most K elements in the dequeue.

Optimized Solutions

Java

View on GeeksforGeeks
import java.util.Deque;
import java.util.LinkedList;

public class MaximumOfAllSubarrays {
    public static void findMax(int[] arr, int k) {
        Deque<Integer> deque = new LinkedList<>();
        int max = Integer.MIN_VALUE;
        
        for (int i = 0; i < k; i++) {
            while (!deque.isEmpty() && deque.peekFirst() <= i - k) {
                deque.pollFirst();
            }
            deque.offer(i);
            max = Math.max(max, arr[i]);
        }
        
        for (int i = k; i < arr.length; i++) {
            if (!deque.isEmpty() && deque.peekFirst() == i - k) {
                deque.pollFirst();
            }
            deque.offer(i);
            max = Math.max(max, arr[i]);
        }
        
        System.out.println("Maximum of all subarrays of size " + k + ": " + max);
    }

    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4, 5};
        int k = 3;
        findMax(arr, k);
    }
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.