Minimum difference between max and min of all K | Java program to find minimum difference between max and min of all subset of K size ; 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
import java . util . Arrays ; class GFG { static int minDifferenceAmongMaxMin ( int arr [ ] , int N , int K ) { Arrays . sort ( arr ) ; int res = 2147483647 ; for ( int i = 0 ; i <= ( N - K ) ; i ++ ) { int curSeqDiff = arr [ i + K - 1 ] - arr [ i ] ; res = Math . min ( res , curSeqDiff ) ; } return res ; } public static void main ( String [ ] args ) { int arr [ ] = { 10 , 20 , 30 , 100 , 101 , 102 } ; int N = arr . length ; int K = 3 ; System . out . print ( minDifferenceAmongMaxMin ( arr , N , K ) ) ; } }