Maximum difference between group of k | java to find maximum group difference ; utility function for array sum ; function for finding maximum group difference of array ; sort the array ; find array sum ; difference for k - smallest diff1 = ( arraysum - k_smallest ) - k_smallest ; reverse array for finding sum of 1 st k - largest ; difference for k - largest diff2 = ( arraysum - k_largest ) - k_largest ; return maximum difference value ; driver program
import java . util . Arrays ; public class GFG { static long arraySum ( int arr [ ] , int n ) { long sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) sum = sum + arr [ i ] ; return sum ; } static long maxDiff ( int arr [ ] , int n , int k ) { Arrays . sort ( arr ) ; long arraysum = arraySum ( arr , n ) ; long diff1 = Math . abs ( arraysum - 2 * arraySum ( arr , k ) ) ; int end = arr . length - 1 ; int start = 0 ; while ( start < end ) { int temp = arr [ start ] ; arr [ start ] = arr [ end ] ; arr [ end ] = temp ; start ++ ; end -- ; } long diff2 = Math . abs ( arraysum - 2 * arraySum ( arr , k ) ) ; return ( Math . max ( diff1 , diff2 ) ) ; } public static void main ( String args [ ] ) { int arr [ ] = { 1 , 7 , 4 , 8 , - 1 , 5 , 2 , 1 } ; int n = arr . length ; int k = 3 ; System . out . println ( " Maximum ▁ Difference ▁ = ▁ " + maxDiff ( arr , n , k ) ) ; } }