Minimize the maximum difference between adjacent elements in an array | Javascript 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
function countSetBits ( x ) { let setBits = 0 ; while ( x != 0 ) { x = x & ( x - 1 ) ; setBits ++ ; } return setBits ; } function minimumAdjacentDifference ( a , n , k ) { let minDiff = Number . MAX_VALUE ; for ( let i = 0 ; i < ( 1 << n ) ; i ++ ) { let cnt = countSetBits ( i ) ; if ( cnt == n - k ) { let temp = [ ] ; for ( let j = 0 ; j < n ; j ++ ) { if ( ( i & ( 1 << j ) ) != 0 ) temp . push ( a [ j ] ) ; } let maxDiff = Number . MIN_VALUE ; for ( let j = 0 ; j < temp . length - 1 ; j ++ ) { maxDiff = Math . max ( maxDiff , temp [ j + 1 ] - temp [ j ] ) ; } minDiff = Math . min ( minDiff , maxDiff ) ; } } return minDiff ; } let n = 5 ; let k = 2 ; let a = [ 3 , 7 , 8 , 10 , 14 ] ; document . write ( minimumAdjacentDifference ( a , n , k ) ) ;