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
< ? php function minDiff ( $ arr , $ n , $ k ) { $ INT_MAX = 2147483647 ; $ result = $ INT_MAX ; sort ( $ arr , $ n ) ; sort ( $ arr ) ; for ( $ i = 0 ; $ i <= $ n - $ k ; $ i ++ ) $ result = min ( $ result , $ arr [ $ i + $ k - 1 ] - $ arr [ $ i ] ) ; return $ result ; } $ arr = array ( 10 , 100 , 300 , 200 , 1000 , 20 , 30 ) ; $ n = sizeof ( $ arr ) ; $ k = 3 ; echo minDiff ( $ arr , $ n , $ k ) ; ? >