Minimize the maximum difference between adjacent elements in an array | C ++ implementation to find the minimum of the maximum difference of the adjacent elements after removing K elements from the array ; Function to find the minimum of the maximum difference of the adjacent elements after removing K elements from the array ; Initialising the minimum difference ; Traversing over subsets in iterative manner ; Number of elements to be taken in the subset ON bits of i represent elements not to be removed ; If the removed set is of size k ; Creating the new array after removing elements ; Maximum difference of adjacent elements of remaining array ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minimumAdjacentDifference ( vector < int > a , int n , int k ) { int minDiff = INT_MAX ; for ( int i = 0 ; i < ( 1 << n ) ; i ++ ) { int cnt = __builtin_popcount ( i ) ; if ( cnt == n - k ) { vector < int > temp ; for ( int j = 0 ; j < n ; j ++ ) { if ( ( i & ( 1 << j ) ) != 0 ) temp . push_back ( a [ j ] ) ; } int maxDiff = INT_MIN ; for ( int j = 0 ; j < temp . size ( ) - 1 ; j ++ ) { maxDiff = max ( maxDiff , temp [ j + 1 ] - temp [ j ] ) ; } minDiff = min ( minDiff , maxDiff ) ; } } return minDiff ; } int main ( ) { int n = 5 ; int k = 2 ; vector < int > a = { 3 , 7 , 8 , 10 , 14 } ; cout << minimumAdjacentDifference ( a , n , k ) ; return 0 ; }