Rearrange an array to minimize sum of product of consecutive pair elements | Javascript program to sort an array such that sum of product of alternate element is minimum . ; create evenArr [ ] and oddArr [ ] ; sort main array in ascending order ; Put elements in oddArr [ ] and evenArr [ ] as per desired value . ; sort evenArr [ ] in descending order ; merge both sub - array and calculate minimum sum of product of alternate elements ; Driver program
function minSum ( arr , n ) { let evenArr = [ ] ; let oddArr = [ ] ; arr . sort ( function ( a , b ) { return a - b ; } ) ; for ( let i = 0 ; i < n ; i ++ ) { if ( i < Math . floor ( n / 2 ) ) { oddArr . push ( arr [ i ] ) ; } else { evenArr . push ( arr [ i ] ) ; } } evenArr . sort ( function ( a , b ) { return b - a ; } ) ; let i = 0 , sum = 0 ; for ( let j = 0 ; j < evenArr . length ; j ++ ) { arr [ i ++ ] = evenArr [ j ] ; arr [ i ++ ] = oddArr [ j ] ; sum += evenArr [ j ] * oddArr [ j ] ; } return sum ; } let arr = [ 1 , 5 , 8 , 9 , 6 , 7 , 3 , 4 , 2 , 0 ] ; let n = arr . length ; document . write ( " " + minSum ( arr , n ) + " " ) ; document . write ( " " ) ; for ( let i = 0 ; i < n ; i ++ ) { document . write ( arr [ i ] + " " ) ; }