Given an array of integers and a number k
, find the maximum element in each subarray of size k
in the array.
Input/Output Examples
plaintext
Example 1:
Input:
arr = [1, 3, -1, -3, 5, 3, 6, 7]
k = 3
Output:
[3, 3, 5, 5, 6, 7]
Explanation: The subarrays of size k=3 are: [1, 3, -1], [3, -1, -3], [ -1, -3, 5], etc. The maximum values are 3, 3, 5, 5, 6, 7.
Example 2:
Input:
arr = [9, 7, 2, 4, 6, 8, 2, 1]
k = 4
Output:
[9, 7, 6, 8, 8]
Explanation: The subarrays of size k=4 are: [9, 7, 2, 4], [7, 2, 4, 6], etc. The maximum values are 9, 7, 6, 8, 8.
Approach to Find the Maximum of All Subarrays of Size k
- Using a Deque (Efficient Sliding Window Approach):
- Use a deque (double-ended queue) to store the indices of the array elements. The deque will store indices in such a way that the front of the deque will always contain the index of the largest element for the current window of size
k
. - Slide the window from the left to the right of the array. For each element:
- Remove indices from the back of the deque if the corresponding element is smaller than the current element.
- Remove the index from the front of the deque if it falls out of the window.
- Add the current element’s index to the deque.
- The element at the front of the deque is the maximum for the current window.
- Use a deque (double-ended queue) to store the indices of the array elements. The deque will store indices in such a way that the front of the deque will always contain the index of the largest element for the current window of size
- Edge Cases:
- If
k
is greater than the size of the array, return an empty array. - If the array is empty, return an empty array.
- If
C++ Program to Find the Maximum of All Subarrays of Size k
cpp
#include <iostream>
#include <deque>
#include <vector>
using namespace std;
// Function to find the maximum of all subarrays of size k
vector<int> maxSlidingWindow(vector<int>& arr, int k) {
deque<int> dq;
vector<int> result;
for (int i = 0; i < arr.size(); i++) {
// Remove elements that are out of this window
if (!dq.empty() && dq.front() == i - k) {
dq.pop_front();
}
// Remove elements that are smaller than the current element
while (!dq.empty() && arr[dq.back()] < arr[i]) {
dq.pop_back();
}
// Add the current element at the back of the deque
dq.push_back(i);
// The front of the deque is the maximum of the current window
if (i >= k - 1) {
result.push_back(arr[dq.front()]);
}
}
return result;
}
int main() {
vector<int> arr = {1, 3, -1, -3, 5, 3, 6, 7};
int k = 3;
vector<int> result = maxSlidingWindow(arr, k);
for (int num : result) {
cout << num << " ";
}
cout << endl;
return 0;
}
Java Program to Find the Maximum of All Subarrays of Size k
java
import java.util.Deque;
import java.util.LinkedList;
import java.util.ArrayList;
import java.util.List;
public class MaxSlidingWindow {
// Function to find the maximum of all subarrays of size k
public static List<Integer> maxSlidingWindow(int[] arr, int k) {
Deque<Integer> deque = new LinkedList<>();
List<Integer> result = new ArrayList<>();
for (int i = 0; i < arr.length; i++) {
// Remove elements that are out of this window
if (!deque.isEmpty() && deque.peekFirst() == i - k) {
deque.pollFirst();
}
// Remove elements that are smaller than the current element
while (!deque.isEmpty() && arr[deque.peekLast()] < arr[i]) {
deque.pollLast();
}
// Add the current element at the back of the deque
deque.addLast(i);
// The front of the deque is the maximum of the current window
if (i >= k - 1) {
result.add(arr[deque.peekFirst()]);
}
}
return result;
}
public static void main(String[] args) {
int[] arr = {1, 3, -1, -3, 5, 3, 6, 7};
int k = 3;
List<Integer> result = maxSlidingWindow(arr, k);
for (int num : result) {
System.out.print(num + " ");
}
System.out.println();
}
}
Python Program to Find the Maximum of All Subarrays of Size k
python
from collections import deque
# Function to find the maximum of all subarrays of size k
def max_sliding_window(arr, k):
dq = deque()
result = []
for i in range(len(arr)):
# Remove elements that are out of this window
if dq and dq[0] == i - k:
dq.popleft()
# Remove elements that are smaller than the current element
while dq and arr[dq[-1]] < arr[i]:
dq.pop()
# Add the current element at the back of the deque
dq.append(i)
# The front of the deque is the maximum of the current window
if i >= k - 1:
result.append(arr[dq[0]])
return result
# Example usage
if __name__ == "__main__":
arr = [1, 3, -1, -3, 5, 3, 6, 7]
k = 3
print("Maximums of all subarrays of size k:", max_sliding_window(arr, k))
- Time Complexity:
O(n)
, wheren
is the number of elements in the array. Each element is pushed and popped from the deque at most once. - Space Complexity:
O(k)
, wherek
is the size of the sliding window. This is the maximum size of the deque at any time.