Choose k array elements such that difference of maximum and minimum is minimized | Return minimum difference of maximum and minimum of k elements of arr [ 0. . n - 1 ] . ; Sorting the array . ; Find minimum value among all K size subarray . ; Driver code
function minDiff ( arr , n , k ) { var result = Number . MAX_VALUE ; arr . sort ( ( a , b ) => a - b ) ; for ( i = 0 ; i <= n - k ; i ++ ) result = Math . min ( result , arr [ i + k - 1 ] - arr [ i ] ) ; return result ; } var arr = [ 10 , 100 , 300 , 200 , 1000 , 20 , 30 ] ; var n = arr . length ; var k = 3 ; document . write ( minDiff ( arr , n , k ) ) ;