Choose k array elements such that difference of maximum and minimum is minimized | C # program to find minimum difference of maximum and minimum of K number . ; 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
using System ; class GFG { static int minDiff ( int [ ] arr , int n , int k ) { int result = int . MaxValue ; Array . Sort ( arr ) ; for ( int i = 0 ; i <= n - k ; i ++ ) result = Math . Min ( result , arr [ i + k - 1 ] - arr [ i ] ) ; return result ; } public static void Main ( ) { int [ ] arr = { 10 , 100 , 300 , 200 , 1000 , 20 , 30 } ; int n = arr . Length ; int k = 3 ; Console . WriteLine ( minDiff ( arr , n , k ) ) ; } }