Minimize difference between the largest and smallest array elements by K replacements
Last Updated :
01 Aug, 2022
Given an array A[] consisting of N integers, the task is to find the minimum difference between the largest and the smallest element in the given array after replacing K elements.
Examples:
Input: A[] = {-1, 3, -1, 8, 5, 4}, K = 3
Output: 2
Explanation:Replace A[0] and A[2] by 3 and 4 respectively. Replace A[3] by 5. Modified array A[] is {3, 3, 4, 5, 5, 4}. Therefore, required output = (5-3) = 2.
Input: A[] = {10, 10, 3, 4, 10}, K = 2
Output: 0
Sorting Approach: The idea is to sort the given array.
- Check for all K + 1 possibilities of
- removing X ( 0 ? X ? K ) elements from the start of the array, and
- removing K – X elements from the end of the array
- Then calculate the minimum difference possible.
- Finally, print the minimum difference obtained.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int minDiff( int A[], int K, int n)
{
sort(A, A + n);
if (n <= K)
return 0;
int mindiff = A[n - 1] - A[0];
if (K == 0)
return mindiff;
for ( int i = 0, j = n - 1 - K; j < n;) {
mindiff = min(mindiff, A[j] - A[i]);
i++;
j++;
}
return mindiff;
}
int main()
{
int A[] = { -1, 3, -1, 8, 5, 4 };
int K = 3;
int n = sizeof (A) / sizeof (A[0]);
cout << minDiff(A, K, n);
return 0;
}
|
Java
import java.util.*;
class GFG {
static int minDiff( int [] A, int K)
{
Arrays.sort(A);
int n = A.length;
if (n <= K)
return 0 ;
int mindiff = A[n - 1 ] - A[ 0 ];
if (K == 0 )
return mindiff;
for ( int i = 0 , j = n - 1 - K; j < n;) {
mindiff = Math.min(mindiff, A[j] - A[i]);
i++;
j++;
}
return mindiff;
}
public static void main(String[] args)
{
int A[] = { - 1 , 3 , - 1 , 8 , 5 , 4 };
int K = 3 ;
System.out.println(minDiff(A, K));
}
}
|
Python3
def minDiff(A, K):
A.sort()
n = len (A)
if (n < = K):
return 0
mindiff = A[n - 1 ] - A[ 0 ]
if (K = = 0 ):
return mindiff
i = 0
for j in range (n - 1 - K, n):
mindiff = min (mindiff, A[j] - A[i])
i + = 1
j + = 1
return mindiff
if __name__ = = '__main__' :
A = [ - 1 , 3 , - 1 , 8 , 5 , 4 ]
K = 3
print (minDiff(A, K))
|
C#
using System;
class GFG {
static int minDiff( int [] A, int K)
{
Array.Sort(A);
int n = A.Length;
if (n <= K)
return 0;
int mindiff = A[n - 1] - A[0];
if (K == 0)
return mindiff;
for ( int i = 0, j = n - 1 - K; j < n;) {
mindiff = Math.Min(mindiff, A[j] - A[i]);
i++;
j++;
}
return mindiff;
}
public static void Main(String[] args)
{
int [] A = { -1, 3, -1, 8, 5, 4 };
int K = 3;
Console.WriteLine(minDiff(A, K));
}
}
|
Javascript
<script>
function minDiff(A, K)
{
A.sort( function (a, b){ return a - b});
let n = A.length;
if (n <= K)
return 0;
let mindiff = A[n - 1] - A[0];
if (K == 0)
return mindiff;
for (let i = 0, j = n - 1 - K; j < n;)
{
mindiff = Math.min(mindiff, A[j] - A[i]);
i++;
j++;
}
return mindiff;
}
let A = [ -1, 3, -1, 8, 5, 4 ];
let K = 3;
document.write(minDiff(A, K));
</script>
|
Time Complexity: O(NlogN)
Auxiliary Space: O(1)
Heap-based Approach: This approach is similar to the above approach, but we will find the K minimum and K maximum array elements using Min Heap and Max Heap respectively.
Follow the steps below to solve the problem:
- Initialize two PriorityQueues, min-heap and max-heap.
- Traverse the given array and add all elements one by one into the Heaps. If the size of the Heap exceeds K, in any of the heaps, remove the element present at the top of that Queue.
- Store the K maximum and the minimum elements in two separate arrays, maxList and minList, and initialize a variable, say minDiff to store the minimum difference.
- Iterate over the arrays and for every index, say i, update minDiff as minDiff = min(minDiff, maxList[i]-minList[ K – i ]) and print final value of minDiff as the required answer.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int minDiff( int A[], int K, int N)
{
if (N <= K + 1)
return 0;
priority_queue< int , vector< int >, greater< int > > maxHeap;
priority_queue< int > minHeap;
for ( int i = 0; i < N; i++) {
maxHeap.push(A[i]);
if (maxHeap.size() > K + 1)
maxHeap.pop();
minHeap.push(A[i]);
if (minHeap.size() > K + 1)
minHeap.pop();
}
vector< int > maxList;
while (maxHeap.size() > 0) {
maxList.push_back(maxHeap.top());
maxHeap.pop();
}
vector< int > minList;
while (minHeap.size() > 0) {
minList.push_back(minHeap.top());
minHeap.pop();
}
int mindiff = INT_MAX;
for ( int i = 0; i <= K; i++) {
mindiff = min(mindiff, maxList[i] - minList[K - i]);
}
return mindiff;
}
int main()
{
int A[] = { -1, 3, -1, 8, 5, 4 };
int N = sizeof (A) / sizeof (A[0]);
int K = 3;
cout << minDiff(A, K, N);
return 0;
}
|
Java
import java.lang.*;
import java.util.*;
class GFG {
static int minDiff( int [] A, int K)
{
if (A.length <= K + 1 )
return 0 ;
PriorityQueue<Integer> maxHeap
= new PriorityQueue<>();
PriorityQueue<Integer> minHeap
= new PriorityQueue<>(
Collections.reverseOrder());
for ( int n : A) {
maxHeap.add(n);
if (maxHeap.size() > K + 1 )
maxHeap.poll();
minHeap.add(n);
if (minHeap.size() > K + 1 )
minHeap.poll();
}
List<Integer> maxList = new ArrayList<>();
while (maxHeap.size() > 0 )
maxList.add(maxHeap.poll());
List<Integer> minList = new ArrayList<>();
while (minHeap.size() > 0 )
minList.add(minHeap.poll());
int mindiff = Integer.MAX_VALUE;
for ( int i = 0 ; i <= K; i++) {
mindiff = Math.min(mindiff,
maxList.get(i)
- minList.get(K - i));
}
return mindiff;
}
public static void main(String[] args)
{
int A[] = { - 1 , 3 , - 1 , 8 , 5 , 4 };
int K = 3 ;
System.out.println(minDiff(A, K));
}
}
|
Python3
import sys
import heapq
def minDiff(A, K):
if ( len (A) < = K + 1 ):
return 0
maxHeap = []
heapq.heapify(maxHeap)
minHeap = []
heapq.heapify(minHeap)
for n in A:
heapq.heappush(maxHeap, n)
if ( len (maxHeap) > K + 1 ):
heapq.heappop(maxHeap)
heapq.heappush(minHeap, - n)
if ( len (minHeap) > K + 1 ):
heapq.heappop(minHeap)
maxList = []
while ( len (maxHeap) > 0 ):
maxList.append(heapq.heappop(maxHeap))
minList = []
while ( len (minHeap) > 0 ):
minList.append( - 1 * heapq.heappop(minHeap))
mindiff = sys.maxsize
for i in range (K):
mindiff = min (mindiff, maxList[i] - minList[K - i])
return mindiff
if __name__ = = "__main__" :
A = [ - 1 , 3 , - 1 , 8 , 5 , 4 ]
K = 3
print (minDiff(A, K))
|
C#
using System;
using System.Collections.Generic;
class GFG {
static int minDiff( int [] A, int K)
{
if (A.Length <= K + 1)
return 0;
List< int > maxHeap = new List< int >();
List< int > minHeap = new List< int >();
foreach ( int n in A)
{
maxHeap.Add(n);
maxHeap.Sort();
if (maxHeap.Count > K + 1)
maxHeap.RemoveAt(0);
minHeap.Add(n);
minHeap.Sort();
minHeap.Reverse();
if (minHeap.Count > K + 1)
minHeap.RemoveAt(0);
}
List< int > maxList = new List< int >();
while (maxHeap.Count > 0) {
maxList.Add(maxHeap[0]);
maxHeap.RemoveAt(0);
}
List< int > minList = new List< int >();
while (minHeap.Count > 0) {
minList.Add(minHeap[0]);
minHeap.RemoveAt(0);
}
int mindiff = Int32.MaxValue;
for ( int i = 0; i < K; i++) {
mindiff = Math.Min(mindiff,
maxList[i] - minList[K - i]);
}
return mindiff;
}
static void Main()
{
int [] A = { -1, 3, -1, 8, 5, 4 };
int K = 3;
Console.WriteLine(minDiff(A, K));
}
}
|
Javascript
<script>
function minDiff(A, K, N)
{
if (N <= K + 1)
return 0;
var maxHeap = [];
var minHeap = [];
for ( var i = 0; i < N; i++)
{
maxHeap.push(A[i]);
maxHeap.sort((a,b)=>b-a);
if (maxHeap.length > K + 1)
maxHeap.pop();
minHeap.push(A[i]);
minHeap.sort((a,b)=>a-b);
if (minHeap.length > K + 1)
minHeap.pop();
}
var maxList = [];
while (maxHeap.length > 0)
{
maxList.push(maxHeap[maxHeap.length-1]);
maxHeap.pop();
}
var minList = [];
while (minHeap.length > 0)
{
minList.push(minHeap[minHeap.length-1]);
minHeap.pop();
}
var mindiff = 1000000000;
for ( var i = 0; i <= K; i++)
{
mindiff = Math.min(mindiff, maxList[i] - minList[K - i]);
}
return mindiff;
}
var A = [-1, 3, -1, 8, 5, 4];
var N = A.length;
var K = 3;
document.write(minDiff(A, K, N));
</script>
|
Time Complexity: O(N*log N) where N is the size of the given array.
Auxiliary Space: O(N)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...