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
def minDiff ( arr , n , k ) : NEW_LINE INDENT result = + 2147483647 NEW_LINE arr . sort ( ) NEW_LINE for i in range ( n - k + 1 ) : NEW_LINE INDENT result = int ( min ( result , arr [ i + k - 1 ] - arr [ i ] ) ) NEW_LINE DEDENT return result NEW_LINE DEDENT arr = [ 10 , 100 , 300 , 200 , 1000 , 20 , 30 ] NEW_LINE n = len ( arr ) NEW_LINE k = 3 NEW_LINE print ( minDiff ( arr , n , k ) ) NEW_LINE