Split array into K non | Java program for the above approach ; Function find maximum sum of minimum and maximum of K subsets ; Stores the result ; Sort the array arr [ ] in decreasing order ; Traverse the range [ 0 , K ] ; Sort the array S [ ] in ascending order ; Traverse the array S [ ] ; If S { i ] is 1 ; Stores the index of the minimum element of the i - th subset ; Traverse the array S [ ] ; Update the counter ; Return the resultant sum ; Driver Code
import java . io . * ; import java . lang . * ; import java . util . * ; class GFG { static int maximumSum ( int arr [ ] , int S [ ] , int N , int K ) { int ans = 0 ; Arrays . sort ( arr ) ; for ( int i = 0 ; i < N / 2 ; i ++ ) { int temp = arr [ i ] ; arr [ i ] = arr [ N - 1 - i ] ; arr [ N - 1 - i ] = temp ; } for ( int i = 0 ; i < K ; i ++ ) ans += arr [ i ] ; Arrays . sort ( S ) ; for ( int i = 0 ; i < K ; i ++ ) { if ( S [ i ] == 1 ) ans += arr [ i ] ; S [ i ] -- ; } int counter = K - 1 ; for ( int i = 0 ; i < K ; i ++ ) { counter = counter + S [ i ] ; if ( S [ i ] != 0 ) ans += arr [ counter ] ; } return ans ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 13 , 7 , 17 } ; int S [ ] = { 1 , 3 } ; int N = arr . length ; int K = S . length ; System . out . println ( maximumSum ( arr , S , N , K ) ) ; } }