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
using System ; using System . Collections . Generic ; class GFG { static int minimumAdjacentDifference ( int [ ] a , int n , int k ) { int minDiff = int . MaxValue ; for ( int i = 0 ; i < ( 1 << n ) ; i ++ ) { int cnt = countSetBits ( i ) ; if ( cnt == n - k ) { List < int > temp = new List < int > ( ) ; for ( int j = 0 ; j < n ; j ++ ) { if ( ( i & ( 1 << j ) ) != 0 ) temp . Add ( a [ j ] ) ; } int maxDiff = int . MinValue ; for ( int j = 0 ; j < temp . Count - 1 ; j ++ ) { maxDiff = Math . Max ( maxDiff , temp [ j + 1 ] - temp [ j ] ) ; } minDiff = Math . Min ( minDiff , maxDiff ) ; } } return minDiff ; } static int countSetBits ( int x ) { int setBits = 0 ; while ( x != 0 ) { x = x & ( x - 1 ) ; setBits ++ ; } return setBits ; } public static void Main ( String [ ] args ) { int n = 5 ; int k = 2 ; int [ ] a = { 3 , 7 , 8 , 10 , 14 } ; Console . WriteLine ( minimumAdjacentDifference ( a , n , k ) ) ; } }