Minimize difference between maximum and minimum array elements by removing a K-length subarray
Last Updated :
13 Oct, 2022
Given an array arr[] consisting of N integers and an integer K, the task is to find the minimum difference between the maximum and minimum element present in the array after removing any subarray of size K.
Examples:
Input: arr[] = {4, 5, 8, 9, 1, 2}, K = 2
Output: 4
Explanation: Remove the subarray {8, 9}. The minimum difference between maximum and minimum array elements becomes (5 - 1) = 4.
Input: arr[] = {1, 2, 2}, K = 1
Output: 0
Explanation: Remove subarray {1}. The minimum difference between maximum and minimum array elements becomes (2 - 2) = 0.
Â
Naive Approach: The simplest approach is to remove all possible subarrays of size K one by one and calculate the difference between maximum and minimum among the remaining elements. Finally, print the minimum difference obtained.
Time Complexity: O(N2)
Auxiliary Space: O(1)
Efficient Approach: The above approach can be optimized by storing maximum and minimum prefixes upto any index and storing the maximum and minimum suffixes starting from any index. Once the above four values are calculated, find the maximum and minimum array elements after removing a K-length subarray in constant computational complexity.Â
Follow the steps below to solve the problem:
- Initialize arrays maxSufix[] and minSuffix[]. such that ith element of maxSuffix[] and minSuffix[] array denotes the maximum and minimum elements respectively present at the right of the ith index.
- Initialize two variables, say maxPrefix and minPrefix, to store the maximum and minimum elements present in the prefix subarray.
- Traverse the array over the indices [1, N] and check if i + K <= N or not. If found to be true, then perform the following steps:
- The maximum value present in the array after removing a subarray of size K starting from ith index is max(maxSuffix[i + k], maxPrefix).
- The minimum value present in the array after removing a subarray of size K starting from ith index is min(minSuffix[i + k], minPrefix).
- Update minDiff to min( minDiff, maximum - minimum), to store the minimum difference.
- Print minDiff as the required answer.
Below is the implementation of the above approach:
C++
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to minimize difference
// between maximum and minimum array
// elements by removing a K-length subarray
void minimiseDifference(vector<int>& arr, int K)
{
// Size of array
int N = arr.size();
// Stores the maximum and minimum
// in the suffix subarray [i .. N-1]
int maxSuffix[N + 1], minSuffix[N + 1];
maxSuffix[N] = -1e9;
minSuffix[N] = 1e9;
maxSuffix[N - 1] = arr[N - 1];
minSuffix[N - 1] = arr[N - 1];
// Constructing the maxSuffix and
// minSuffix arrays
// Traverse the array
for (int i = N - 2; i >= 0; --i) {
maxSuffix[i] = max(
maxSuffix[i + 1],
arr[i]);
minSuffix[i] = min(
minSuffix[i + 1],
arr[i]);
}
// Stores the maximum and minimum
// in the prefix subarray [0 .. i-1]
int maxPrefix = arr[0];
int minPrefix = arr[0];
// Store the minimum difference
int minDiff = maxSuffix[K] - minSuffix[K];
// Traverse the array
for (int i = 1; i < N; ++i) {
// If the suffix doesn't exceed
// the end of the array
if (i + K <= N) {
// Store the maximum element
// in array after removing
// subarray of size K
int maximum = max(maxSuffix[i + K], maxPrefix);
// Stores the maximum element
// in array after removing
// subarray of size K
int minimum = min(minSuffix[i + K], minPrefix);
// Update minimum difference
minDiff = min(minDiff, maximum - minimum);
}
// Updating the maxPrefix and
// minPrefix with current element
maxPrefix = max(maxPrefix, arr[i]);
minPrefix = min(minPrefix, arr[i]);
}
// Print the minimum difference
cout << minDiff << "\n";
}
// Driver Code
int main()
{
vector<int> arr = { 4, 5, 8, 9, 1, 2 };
int K = 2;
minimiseDifference(arr, K);
return 0;
}
Java
// Java program for the above approach
import java.util.*;
class GFG
{
// Function to minimize difference
// between maximum and minimum array
// elements by removing a K-length subarray
static void minimiseDifference(int[] arr, int K)
{
// Size of array
int N = arr.length;
// Stores the maximum and minimum
// in the suffix subarray [i .. N-1]
int[] maxSuffix = new int[N + 1];
int[] minSuffix = new int[N + 1];
maxSuffix[N] = -1000000000;
minSuffix[N] = 1000000000;
maxSuffix[N - 1] = arr[N - 1];
minSuffix[N - 1] = arr[N - 1];
// Constructing the maxSuffix and
// minSuffix arrays
// Traverse the array
for (int i = N - 2; i >= 0; --i) {
maxSuffix[i]
= Math.max(maxSuffix[i + 1], arr[i]);
minSuffix[i]
= Math.min(minSuffix[i + 1], arr[i]);
}
// Stores the maximum and minimum
// in the prefix subarray [0 .. i-1]
int maxPrefix = arr[0];
int minPrefix = arr[0];
// Store the minimum difference
int minDiff = maxSuffix[K] - minSuffix[K];
// Traverse the array
for (int i = 1; i < N; ++i) {
// If the suffix doesn't exceed
// the end of the array
if (i + K <= N) {
// Store the maximum element
// in array after removing
// subarray of size K
int maximum
= Math.max(maxSuffix[i + K], maxPrefix);
// Stores the maximum element
// in array after removing
// subarray of size K
int minimum
= Math.min(minSuffix[i + K], minPrefix);
// Update minimum difference
minDiff
= Math.min(minDiff, maximum - minimum);
}
// Updating the maxPrefix and
// minPrefix with current element
maxPrefix = Math.max(maxPrefix, arr[i]);
minPrefix = Math.min(minPrefix, arr[i]);
}
// Print the minimum difference
System.out.print(minDiff);
}
// Driver Code
public static void main(String[] args)
{
int[] arr = { 4, 5, 8, 9, 1, 2 };
int K = 2;
minimiseDifference(arr, K);
}
}
// This code is contributed by susmitakundugoaldanga.
Python3
# Python 3 program for the above approach
# Function to minimize difference
# between maximum and minimum array
# elements by removing a K-length subarray
def minimiseDifference(arr, K):
# Size of array
N = len(arr)
# Stores the maximum and minimum
# in the suffix subarray [i .. N-1]
maxSuffix = [0 for i in range(N + 1)]
minSuffix = [0 for i in range(N + 1)]
maxSuffix[N] = -1e9
minSuffix[N] = 1e9
maxSuffix[N - 1] = arr[N - 1]
minSuffix[N - 1] = arr[N - 1]
# Constructing the maxSuffix and
# minSuffix arrays
# Traverse the array
i = N - 2
while(i >= 0):
maxSuffix[i] = max(maxSuffix[i + 1],arr[i])
minSuffix[i] = min(minSuffix[i + 1], arr[i])
i -= 1
# Stores the maximum and minimum
# in the prefix subarray [0 .. i-1]
maxPrefix = arr[0]
minPrefix = arr[0]
# Store the minimum difference
minDiff = maxSuffix[K] - minSuffix[K]
# Traverse the array
for i in range(1, N):
# If the suffix doesn't exceed
# the end of the array
if (i + K <= N):
# Store the maximum element
# in array after removing
# subarray of size K
maximum = max(maxSuffix[i + K], maxPrefix)
# Stores the maximum element
# in array after removing
# subarray of size K
minimum = min(minSuffix[i + K], minPrefix)
# Update minimum difference
minDiff = min(minDiff, maximum - minimum)
# Updating the maxPrefix and
# minPrefix with current element
maxPrefix = max(maxPrefix, arr[i])
minPrefix = min(minPrefix, arr[i])
# Print the minimum difference
print(minDiff)
# Driver Code
if __name__ == '__main__':
arr = [4, 5, 8, 9, 1, 2]
K = 2
minimiseDifference(arr, K)
# This code is contributed by SURENDRA_GANGWAR.
C#
// C# program for the above approach
using System;
using System.Collections.Generic;
class GFg {
// Function to minimize difference
// between maximum and minimum array
// elements by removing a K-length subarray
static void minimiseDifference(List<int> arr, int K)
{
// Size of array
int N = arr.Count;
// Stores the maximum and minimum
// in the suffix subarray [i .. N-1]
int[] maxSuffix = new int[N + 1];
int[] minSuffix = new int[N + 1];
maxSuffix[N] = -1000000000;
minSuffix[N] = 1000000000;
maxSuffix[N - 1] = arr[N - 1];
minSuffix[N - 1] = arr[N - 1];
// Constructing the maxSuffix and
// minSuffix arrays
// Traverse the array
for (int i = N - 2; i >= 0; --i) {
maxSuffix[i]
= Math.Max(maxSuffix[i + 1], arr[i]);
minSuffix[i]
= Math.Min(minSuffix[i + 1], arr[i]);
}
// Stores the maximum and minimum
// in the prefix subarray [0 .. i-1]
int maxPrefix = arr[0];
int minPrefix = arr[0];
// Store the minimum difference
int minDiff = maxSuffix[K] - minSuffix[K];
// Traverse the array
for (int i = 1; i < N; ++i) {
// If the suffix doesn't exceed
// the end of the array
if (i + K <= N) {
// Store the maximum element
// in array after removing
// subarray of size K
int maximum
= Math.Max(maxSuffix[i + K], maxPrefix);
// Stores the maximum element
// in array after removing
// subarray of size K
int minimum
= Math.Min(minSuffix[i + K], minPrefix);
// Update minimum difference
minDiff
= Math.Min(minDiff, maximum - minimum);
}
// Updating the maxPrefix and
// minPrefix with current element
maxPrefix = Math.Max(maxPrefix, arr[i]);
minPrefix = Math.Min(minPrefix, arr[i]);
}
// Print the minimum difference
Console.WriteLine(minDiff);
}
// Driver Code
public static void Main()
{
List<int> arr
= new List<int>() { 4, 5, 8, 9, 1, 2 };
int K = 2;
minimiseDifference(arr, K);
}
}
// This code is contributed by chitranayal.
JavaScript
<script>
// JavaScript program for the above approach
// Function to minimize difference
// between maximum and minimum array
// elements by removing a K-length subarray
function minimiseDifference(arr, K)
{
// Size of array
var N = arr.length;
// Stores the maximum and minimum
// in the suffix subarray [i .. N-1]
var maxSuffix = new Array(N + 1);
var minSuffix = new Array(N + 1);
maxSuffix[N] = -1e9;
minSuffix[N] = 1e9;
maxSuffix[N - 1] = arr[N - 1];
minSuffix[N - 1] = arr[N - 1];
// Constructing the maxSuffix and
// minSuffix arrays
// Traverse the array
for (var i = N - 2; i >= 0; --i) {
maxSuffix[i] = Math.max(maxSuffix[i + 1], arr[i]);
minSuffix[i] = Math.min(minSuffix[i + 1], arr[i]);
}
// Stores the maximum and minimum
// in the prefix subarray [0 .. i-1]
var maxPrefix = arr[0];
var minPrefix = arr[0];
// Store the minimum difference
var minDiff = maxSuffix[K] - minSuffix[K];
// Traverse the array
for (var i = 1; i < N; ++i) {
// If the suffix doesn't exceed
// the end of the array
if (i + K <= N) {
// Store the maximum element
// in array after removing
// subarray of size K
var maximum =
Math.max(maxSuffix[i + K], maxPrefix);
// Stores the maximum element
// in array after removing
// subarray of size K
var minimum =
Math.min(minSuffix[i + K], minPrefix);
// Update minimum difference
minDiff =
Math.min(minDiff, maximum - minimum);
}
// Updating the maxPrefix and
// minPrefix with current element
maxPrefix = Math.max(maxPrefix, arr[i]);
minPrefix = Math.min(minPrefix, arr[i]);
}
// Print the minimum difference
document.write( minDiff + "<br>");
}
var arr = [ 4, 5, 8, 9, 1, 2 ];
var K = 2;
minimiseDifference(arr, K);
// This code is contributed by SoumikMondal
</script>
Â
Â
Time Complexity: O(N)
Auxiliary Space: O(N)Â
Related Topic: Subarrays, Subsequences, and Subsets in Array
Similar Reads
Minimize difference between maximum and minimum array elements by exactly K removals Given an array arr[] consisting of N positive integers and an integer K, the task is to minimize the difference between the maximum and minimum element in the given array after removing exactly K elements. Examples: Input: arr[] = {5, 1, 6, 7, 12, 10}, K = 3Output: 2Explanation:Remove elements 12, 1
6 min read
Split a given array into K subarrays minimizing the difference between their maximum and minimum Given a sorted array arr[] of N integers and an integer K, the task is to split the array into K subarrays such that the sum of the difference of maximum and minimum element of each subarray is minimized. Examples: Input: arr[] = {1, 3, 3, 7}, K = 4 Output: 0 Explanation: The given array can be spli
6 min read
Split array into K Subarrays to minimize sum of difference between min and max Given a sorted array arr[] of size N and integer K, the task is to split the array into K non-empty subarrays such that the sum of the difference between the maximum element and the minimum element of each subarray is minimized. Note: Every element of the array must be included in one subarray and e
6 min read
Minimize count of array elements to be removed to maximize difference between any pair up to K Given an array arr[] and an integer K, the task is to count the number of elements to be removed from the array such that the difference of the maximum and the minimum number left does not exceed K. Examples: Input: K = 1, arr[] = {1, 2, 3, 4, 5} Output: 3 Explanation: Removal of {5, 4, 3} modifies
5 min read
Minimize the difference between the maximum and minimum values of the modified array Given an array A of n integers and integer X. You may choose any integer between -X\leq k\leq X , and add k to A[i] for each 0\leq i \leq n-1 . The task is to find the smallest possible difference between the maximum value of A and the minimum value of A after updating array A. Examples: Input: arr[
5 min read