Minimum and Maximum of all subarrays of size K using Map (original) (raw)
Last Updated : 12 Jan, 2023
Given an array arr[] of N integers and an integer K, the task is to find the minimum and maximum of all subarrays of size K. Examples:
Input: arr[] = {2, -2, 3, -9, -5, -8}, K = 4 Output: -9 3 -9 3 -9 3 Explanation: Below are the subarray of size 4 and minimum and maximum value of each subarray: 1. {2, -2, 3, -9}, minValue = -9, maxValue = 3 2. {-2, 3, -9, -5}, minValue = -9, maxValue = 3 3. {3, -9, -5, -8}, minValue = -9, maxValue = 3 Input: arr[] = { 5, 4, 3, 2, 1, 6, 3, 5, 4, 2, 1 }, K = 3 Output: 3 5 2 4 1 3 1 6 1 6 3 6 3 5 2 5 1 4
Approach:
- Traverse the given array upto K elements and store the count of each element into a map.
- After inserting K elements, for each remaining elements do the following:
- Increase the frequency of current element arr[i] by 1.
- Decrease the frequency of arr[i - K + 1] by 1 to store the frequency of current subarray(arr[i - K + 1, i]) of size K.
- Since map stores the key value pair in sorted order. Therefore the iterator at the starting of the map stores the minimum element and at the ending of the map stores the maximum element. Print the minimum and maximum element of the current subarray.
- Repeat the above steps for each subarray formed.
Below is the implementation of the above approach:
CPP `
// C++ program for the above approach
#include <bits/stdc++.h> using namespace std;
// Function to find the minimum and // maximum element for each subarray // of size K int maxSubarray(int arr[], int n, int k) {
// To store the frequency of element
// for every subarray
map<int, int> Map;
// To count the subarray array size
// while traversing array
int l = 0;
// Traverse the array
for (int i = 0; i < n; i++) {
// Increment till we store the
// frequency of first K element
l++;
// Update the count for current
// element
Map[arr[i]]++;
// If subarray size is K, then
// find the minimum and maximum
// for each subarray
if (l == k) {
// Iterator points to end
// of the Map
auto itMax = Map.end();
itMax--;
// Iterator points to start of
// the Map
auto itMin = Map.begin();
// Print the minimum and maximum
// element of current sub-array
cout << itMin->first << ' '
<< itMax->first << endl;
// Decrement the frequency of
// arr[i - K + 1]
Map[arr[i - k + 1]]--;
// if arr[i - K + 1] is zero
// remove from the map
if (Map[arr[i - k + 1]] == 0) {
Map.erase(arr[i - k + 1]);
}
l--;
}
}
return 0;
}
// Driver Code int main() { // Given array arr[] int arr[] = { 5, 4, 3, 2, 1, 6, 3, 5, 4, 2, 1 };
// Subarray size
int k = 3;
int n = sizeof(arr) / sizeof(arr[0]);
// Function Call
maxSubarray(arr, n, k);
return 0;
}
Java
/*package whatever //do not write package name here / import java.util.;
class GFG {
// Function to find the minimum and // maximum element for each subarray // of size K static int maxSubarray(int arr[], int n, int k) {
// To store the frequency of element
// for every subarray
TreeMap<Integer, Integer> Map = new TreeMap<>();
// To count the subarray array size
// while traversing array
int l = 0;
// Traverse the array
for (int i = 0; i < n; i++) {
// Increment till we store the
// frequency of first K element
l++;
// Update the count for current
// element
Map.put(arr[i],Map.getOrDefault(arr[i],0)+1);
// If subarray size is K, then
// find the minimum and maximum
// for each subarray
if (l == k) {
// Iterator points to end
// of the Map
var itMax = getLast(Map);
// Iterator points to start of
// the Map
var itMin = getFirst(Map);
// Print the minimum and maximum
// element of current sub-array
System.out.println(itMin.getKey() + " " + itMax.getKey());
// Decrement the frequency of
// arr[i - K + 1]
Map.put(arr[i - k + 1],Map.getOrDefault(arr[i - k + 1],0)-1);
// if arr[i - K + 1] is zero
// remove from the map
if (Map.get(arr[i - k + 1]) == 0) {
Map.remove(arr[i - k + 1]);
}
l--;
}
}
return 0;
}
static Map.Entry<Integer, Integer> getFirst(TreeMap<Integer, Integer> lhm){ int count = 1; for (Map.Entry<Integer, Integer> it : lhm.entrySet()) { if (count == 1) { return it; } count++; }
return null;
}
static Map.Entry<Integer, Integer> getLast(TreeMap<Integer, Integer> lhm) { int count = 1;
for (Map.Entry<Integer, Integer> it : lhm.entrySet()) {
if (count == lhm.size()) {
return it;
}
count++;
}
return null;
}
public static void main (String[] args) {
// Given array arr[]
int arr[] = { 5, 4, 3, 2, 1, 6,3, 5, 4, 2, 1 };
// Subarray size
int k = 3;
int n = arr.length;
// Function Call
maxSubarray(arr, n, k);
} }
// This code is contributed by aadityaburujwale.
Python3
Function to find the minimum and
maximum element for each subarray
of size K
def maxSubarray(arr, n, k): # To store the frequency of element # for every subarray map = dict()
# To count the subarray array size
# while traversing array
l = 0
# Traverse the array
for i in range(n):
# Increment till we store the
# frequency of first K element
l += 1
# Update the count for current
# element
if arr[i] in map:
map[arr[i]] += 1
else:
map[arr[i]] = 1
# If subarray size is K, then
# find the minimum and maximum
# for each subarray
if l == k:
# Iterator points to end
# of the Map
itMax = max(map.keys())
# Iterator points to start of
# the Map
itMin = min(map.keys())
# Print the minimum and maximum
# element of current sub-array
print(itMin, itMax)
# Decrement the frequency of
# arr[i - K + 1]
map[arr[i - k + 1]] -= 1
# if arr[i - K + 1] is zero
# remove from the map
if map[arr[i - k + 1]] == 0:
del map[arr[i - k + 1]]
l -= 1
return 0
Given array arr[]
arr = [5, 4, 3, 2, 1, 6, 3, 5, 4, 2, 1]
Subarray size
k = 3
n = len(arr)
Function Call
maxSubarray(arr, n, k)
This code is contributed by akashish__
C#
using System; using System.Collections.Generic;
class GFG { // Function to find the minimum and // maximum element for each subarray // of size K static int maxSubarray(int[] arr, int n, int k) { // To store the frequency of element // for every subarray SortedDictionary<int, int> Map = new SortedDictionary<int, int>();
// To count the subarray array size
// while traversing array
int l = 0;
// Traverse the array
for (int i = 0; i < n; i++)
{
// Increment till we store the
// frequency of first K element
l++;
// Update the count for current
// element
if (!Map.ContainsKey(arr[i]))
{
Map.Add(arr[i], 1);
}
else
{
Map[arr[i]]++;
}
// If subarray size is K, then
// find the minimum and maximum
// for each subarray
if (l == k)
{
// Iterator points to end
// of the Map
var itMax = getLast(Map);
// Iterator points to start of
// the Map
var itMin = getFirst(Map);
// Print the minimum and maximum
// element of current sub-array
Console.WriteLine(itMin.Key + " " + itMax.Key);
// Decrement the frequency of
// arr[i - K + 1]
Map[arr[i - k + 1]]--;
// if arr[i - K + 1] is zero
// remove from the map
if (Map[arr[i - k + 1]] == 0)
{
Map.Remove(arr[i - k + 1]);
}
l--;
}
}
return 0;
}
static KeyValuePair<int, int> getFirst(SortedDictionary<int, int> lhm) { int count = 1; foreach (KeyValuePair<int, int> it in lhm) { if (count == 1) { return it; } count++; }
return default(KeyValuePair<int, int>);
}
static KeyValuePair<int, int> getLast(SortedDictionary<int, int> lhm) { int count = 1;
foreach (KeyValuePair<int, int> it in lhm)
{
if (count == lhm.Count)
{
return it;
}
count++;
}
return default(KeyValuePair<int, int>);
}
public static void Main(string[] args) { // Given array arr[] int[] arr = { 5, 4, 3, 2, 1, 6, 3, 5, 4, 2, 1 };
// Subarray size
int k = 3;
int n = arr.Length;
// Function Call
maxSubarray(arr, n, k);
} }
// This code is contributed by akashish__
JavaScript
// Function to find the minimum and // maximum element for each subarray // of size K function maxSubarray(arr, n, k) { // To store the frequency of element // for every subarray let map = new Map();
// To count the subarray array size // while traversing array let l = 0;
// Traverse the array for (let i = 0; i < n; i++) { // Increment till we store the // frequency of first K element l++;
// Update the count for current
// element
if (map.has(arr[i])) {
map.set(arr[i], map.get(arr[i]) + 1);
} else {
map.set(arr[i], 1);
}
// If subarray size is K, then
// find the minimum and maximum
// for each subarray
if (l === k) {
// Iterator points to end
// of the Map
let itMax = map.keys().next().value;
for (let key of map.keys()) {
itMax = Math.max(itMax, key);
}
// Iterator points to start of
// the Map
let itMin = map.keys().next().value;
for (let key of map.keys()) {
itMin = Math.min(itMin, key);
}
// Print the minimum and maximum
// element of current sub-array
console.log(itMin + " " + itMax);
// Decrement the frequency of
// arr[i - K + 1]
map.set(arr[i - k + 1], map.get(arr[i - k + 1]) - 1);
// if arr[i - K + 1] is zero
// remove from the map
if (map.get(arr[i - k + 1]) === 0) {
map.delete(arr[i - k + 1]);
}
l--;
}
} return 0; }
// Given array arr[] let arr = [5, 4, 3, 2, 1, 6, 3, 5, 4, 2, 1];
// Subarray size let k = 3;
let n = arr.length;
// Function Call maxSubarray(arr, n, k);
// This code is contributed by akashish__
`
Output:
3 5 2 4 1 3 1 6 1 6 3 6 3 5 2 5 1 4
Time Complexity: O(N*log K), where N is the number of element. Auxiliary Space: O(K), where K is the size of subarray.
Similar Reads
- Find maximum (or minimum) sum of a subarray of size k Given an array of integers and a number k, find the maximum sum of a subarray of size k. Examples: Input : arr[] = {100, 200, 300, 400}, k = 2Output : 700Input : arr[] = {1, 4, 2, 10, 23, 3, 1, 0, 20}, k = 4 Output : 39Explanation: We get maximum sum by adding subarray {4, 2, 10, 23} of size 4.Input 14 min read
- Sum of minimum and maximum elements of all subarrays of size k. Given an array of both positive and negative integers, the task is to compute sum of minimum and maximum elements of all sub-array of size k.Examples: Input : arr[] = {2, 5, -1, 7, -3, -1, -2} K = 4Output : 18Explanation : Subarrays of size 4 are : {2, 5, -1, 7}, min + max = -1 + 7 = 6 {5, -1, 7, -3 15+ min read
- Maximum of all Subarrays of size k using set in C++ STL Given an array of size N and an integer K, the task is to find the maximum for each and every contiguous sub-array of size K and print the sum of all these values in the end. Examples: Input: arr[] = {4, 10, 54, 11, 8, 7, 9}, K = 3 Output: 182 Input: arr[] = {1, 2, 3, 4, 1, 6, 7, 8, 2, 1}, K = 4 Out 3 min read
- Sliding Window Maximum (Maximum of all subarrays of size K) Given an array arr[] of integers and an integer k, your task is to find the maximum value for each contiguous subarray of size k. The output should be an array of maximum values corresponding to each contiguous subarray.Examples : Input: arr[] = [1, 2, 3, 1, 4, 5, 2, 3, 6], k = 3Output: [3, 3, 4, 5, 15+ min read
- Maximum of all subarrays of size K using Segment Tree Given an array arr[] 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 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 14 min read
- Sliding Window Maximum (Maximum of all subarrays of size k) using stack in O(n) time Given an array arr[] of N integers and another integer k ? N. The task is to find the maximum element of every sub-array of size k. Examples: Input: arr[] = {9, 7, 2, 4, 6, 8, 2, 1, 5} k = 3 Output: 9 7 6 8 8 8 5 Explanation: Window 1: {9, 7, 2}, max = 9 Window 2: {7, 2, 4}, max = 7 Window 3: {2, 4, 8 min read
- Sum of absolute difference of maximum and minimum of all subarrays Given an array arr containing N integers, the task is to find the sum of the absolute difference of maximum and minimum of all subarrays. Example: Input: arr[] = {1, 4, 3}Output: 7Explanation: The following are the six subarrays:[1] : maximum - minimum= 1 - 1 = 0[4] : maximum - minimum= 4 - 4 = 0[3] 5 min read
- Maximize the sum of maximum elements of at least K-sized subarrays Given an integer array arr[] of length N and an integer K, partition the array in some non-overlapping subarrays such that each subarray has size at least K and each element of the array should be part of a subarray. The task is to maximize the sum of maximum elements across all the subarrays. Examp 7 min read
- Minimum product of maximum and minimum element over all possible subarrays Given an array arr[] consisting of N positive integers, the task is to find the minimum product of maximum and minimum among all possible subarrays. Examples: Input: arr[] = {6, 4, 5, 6, 2, 4}Output: 8Explanation:Consider the subarray {2, 4}, the product of minimum and maximum for this subarray is 2 4 min read
- Minimum common element in all subarrays of size K Given an array arr[] consisting of N distinct integers and a positive integer K, the task is to find the minimum element that occurs in all subarrays of size K. If no such element exists, then print "-1". Examples: Input: arr[] = {1, 2, 3, 4, 5}, K = 4Output: 2Explanation:The subarrays of size 4 are 7 min read