Rearrange array to maximize count of triplets ( i , j , k ) such that arr [ i ] > arr [ j ] < arr [ k ] and i < j < k | Function to rearrange the array to maximize the count of triplets ; Sort the given array ; Stores the permutations of the given array ; Stores the index of the given array ; Place the first half of the given array ; Place the last half of the given array ; Stores the count of triplets ; Check the given conditions ; Driver Code
function ctTriplets ( arr , N ) { arr . sort ( ) ; let temp = [ ] ; let index = 0 ; for ( let i = 1 ; i < N ; i += 2 ) { temp [ i ] = arr [ index ++ ] ; } for ( let i = 0 ; i < N ; i += 2 ) { temp [ i ] = arr [ index ++ ] ; } let ct = 0 ; for ( let i = 0 ; i < N ; i ++ ) { if ( i > 0 && i + 1 < N ) { if ( temp [ i ] < temp [ i + 1 ] && temp [ i ] < temp [ i - 1 ] ) { ct ++ ; } } } document . write ( " " + ct + " " ) ; document . write ( " " ) ; for ( let i = 0 ; i < N ; i ++ ) { document . write ( temp [ i ] + " " ) ; } } let arr = [ 1 , 2 , 3 , 4 , 5 , 6 ] ; let N = arr . length ; ctTriplets ( arr , N ) ;