Minimum difference between max and min of all K | Returns min difference between max and min of any K - size subset ; sort the array so that close elements come together . ; initialize result by a big integer number ; loop over first ( N - K ) elements of the array only ; get difference between max and min of current K - sized segment ; Driver Code
def minDifferenceAmongMaxMin ( arr , N , K ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE res = 2147483647 NEW_LINE for i in range ( ( N - K ) + 1 ) : NEW_LINE INDENT curSeqDiff = arr [ i + K - 1 ] - arr [ i ] NEW_LINE res = min ( res , curSeqDiff ) NEW_LINE DEDENT return res NEW_LINE DEDENT arr = [ 10 , 20 , 30 , 100 , 101 , 102 ] NEW_LINE N = len ( arr ) NEW_LINE K = 3 NEW_LINE print ( minDifferenceAmongMaxMin ( arr , N , K ) ) NEW_LINE