Maximize difference between maximum and minimum array elements after K operations | Java program to implement the above approach ; Reverse array ; Function to find the maximum difference between the maximum and minimum in the array after K operations ; Stores maximum difference between largest and smallest array element ; Sort the array in descending order ; Traverse the array arr [ ] ; Update maxDiff ; Driver Code
import java . util . * ; class GFG { static int [ ] reverse ( int a [ ] ) { int i , n = a . length , t ; for ( i = 0 ; i < n / 2 ; i ++ ) { t = a [ i ] ; a [ i ] = a [ n - i - 1 ] ; a [ n - i - 1 ] = t ; } return a ; } static int maxDiffLargSmallOper ( int arr [ ] , int N , int K ) { int maxDiff = 0 ; Arrays . sort ( arr ) ; arr = reverse ( arr ) ; for ( int i = 0 ; i <= Math . min ( K , N - 1 ) ; i ++ ) { maxDiff += arr [ i ] ; } return maxDiff ; } public static void main ( String [ ] args ) { int arr [ ] = { 7 , 7 , 7 , 7 } ; int N = arr . length ; int K = 1 ; System . out . print ( maxDiffLargSmallOper ( arr , N , K ) ) ; } }