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
function minDifferenceAmongMaxMin ( arr , N , K ) { arr . sort ( ( a , b ) => a - b ) ; let res = 2147483647 ; for ( let i = 0 ; i <= ( N - K ) ; i ++ ) { let curSeqDiff = arr [ i + K - 1 ] - arr [ i ] ; res = Math . min ( res , curSeqDiff ) ; } return res ; } let arr = [ 10 , 20 , 30 , 100 , 101 , 102 ] ; let N = arr . length ; let K = 3 ; document . write ( minDifferenceAmongMaxMin ( arr , N , K ) ) ;