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 ; Array declaration ; Size of array
function formQuadruplets ( arr , n ) { var ans = 0 , pairs = 0 ; pairs = parseInt ( n / 4 ) ; arr . sort ( ) . reverse ( ) ; for ( var i = 0 ; i < n - pairs ; i += 3 ) { ans += arr [ i + 2 ] ; } return ans ; } var arr = [ 2 , 1 , 7 , 5 , 5 , 4 , 1 , 1 , 3 , 3 , 2 , 2 ] ; var n = arr . length ; document . write ( formQuadruplets ( arr , n ) + " " ) ;