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
< ? php function minDifferenceAmongMaxMin ( $ arr , $ N , $ K ) { $ INT_MAX = 2 ; sort ( $ arr ) ; sort ( $ arr , $ N ) ; $ res = $ INT_MAX ; for ( $ i = 0 ; $ i <= ( $ N - $ K ) ; $ i ++ ) { $ curSeqDiff = $ arr [ $ i + $ K - 1 ] - $ arr [ $ i ] ; $ res = min ( $ res , $ curSeqDiff ) ; } return $ res ; } $ arr = array ( 10 , 20 , 30 , 100 , 101 , 102 ) ; $ N = sizeof ( $ arr ) ; $ K = 3 ; echo minDifferenceAmongMaxMin ( $ arr , $ N , $ K ) ; ? >