Minimize count of array elements to be removed to maximize difference between any pair up to K | C ++ Program to implement the above approach ; Function to count the number of elements to be removed from the array based on the given condition ; Sort the array ; / Initialize the variable ; Iterate for all possible pairs ; Check the difference between the numbers ; Update the minimum removals ; Return the answer ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int min_remove ( int arr [ ] , int n , int k ) { sort ( arr , arr + n ) ; int ans = INT_MAX ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = i ; j < n ; j ++ ) { if ( arr [ j ] - arr [ i ] <= k ) { ans = min ( ans , n - j + i - 1 ) ; } } } return ans ; } int main ( ) { int k = 3 ; int arr [ ] = { 1 , 2 , 3 , 4 , 5 } ; int n = sizeof arr / sizeof arr [ 0 ] ; cout << min_remove ( arr , n , k ) ; return 0 ; }