Split array into equal length subsets with maximum sum of Kth largest element of each subset | Java program to implement the above approach ; Function to find the maximum sum of Kth largest element of M equal length partition ; Stores sum of K_th largest element of equal length partitions ; If N is not divisible by M ; Stores length of each partition ; If K is greater than length of partition ; Sort array in descending porder ; Traverse the array ; Update maxSum ; Driver code
import java . util . * ; import java . util . Collections ; class GFG { static int maximumKthLargestsumPart ( int [ ] arr , int N , int M , int K ) { int maxSum = 0 ; if ( N % M != 0 ) return - 1 ; int sz = ( N / M ) ; if ( K > sz ) return - 1 ; Arrays . sort ( arr ) ; int i , k , t ; for ( i = 0 ; i < N / 2 ; i ++ ) { t = arr [ i ] ; arr [ i ] = arr [ N - i - 1 ] ; arr [ N - i - 1 ] = t ; } for ( i = 1 ; i <= M ; i ++ ) { maxSum += arr [ i * K - 1 ] ; } return maxSum ; } public static void main ( String [ ] args ) { int [ ] arr = { 1 , 2 , 3 , 4 , 5 , 6 } ; int M = 2 ; int K = 1 ; int N = arr . length ; System . out . println ( maximumKthLargestsumPart ( arr , N , M , K ) ) ; } }