Maximize 3 rd element sum in quadruplet sets formed from given Array | Java code to Maximize 3 rd element sum in quadruplet sets formed from given Array ; Function to find the maximum possible value of Y ; pairs contain count of minimum elements that will be utilized at place of Z . it is equal to count of possible pairs that is size of array divided by 4 ; sorting the array in descending order so as to bring values with minimal difference closer to arr [ i ] ; here , i + 2 acts as a pointer that points to the third value of every possible quadruplet ; returning the optimally maximum possible value ; Driver code ; array declaration ; size of array
import java . util . * ; class GFG { static int formQuadruplets ( Integer arr [ ] , int n ) { int ans = 0 , pairs = 0 ; pairs = n / 4 ; Arrays . sort ( arr , Collections . reverseOrder ( ) ) ; for ( int i = 0 ; i < n - pairs ; i += 3 ) { ans += arr [ i + 2 ] ; } return ans ; } public static void main ( String [ ] args ) { Integer arr [ ] = { 2 , 1 , 7 , 5 , 5 , 4 , 1 , 1 , 3 , 3 , 2 , 2 } ; int n = arr . length ; System . out . print ( formQuadruplets ( arr , n ) + "NEW_LINE"); } }