Minimize difference between the largest and smallest array elements by K replacements | Java program for the above approach ; Function to find minimum difference between largest and smallest element after K replacements ; Sort array in ascending order ; Length of array ; Minimum difference ; Check for all K + 1 possibilities ; Return answer ; Driver Code ; Given array ; Prints the minimum possible difference
import java . util . * ; class GFG { static int minDiff ( int [ ] A , int K ) { Arrays . sort ( A ) ; int n = A . length ; if ( n <= K ) return 0 ; int mindiff = A [ n - 1 ] - A [ 0 ] ; if ( K == 0 ) return mindiff ; for ( int i = 0 , j = n - 1 - K ; j < n ; ) { mindiff = Math . min ( mindiff , A [ j ] - A [ i ] ) ; i ++ ; j ++ ; } return mindiff ; } public static void main ( String [ ] args ) { int A [ ] = { - 1 , 3 , - 1 , 8 , 5 , 4 } ; int K = 3 ; System . out . println ( minDiff ( A , K ) ) ; } }