Rearrange an array to minimize sum of product of consecutive pair elements | 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 Code
using System ; using System . Collections . Generic ; class GFG { static int minSum ( int [ ] arr , int n ) { List < int > evenArr = new List < int > ( ) ; List < int > oddArr = new List < int > ( ) ; int i ; Array . Sort ( arr ) ; for ( i = 0 ; i < n ; i ++ ) { if ( i < n / 2 ) { oddArr . Add ( arr [ i ] ) ; } else { evenArr . Add ( arr [ i ] ) ; } } evenArr . Sort ( ) ; evenArr . Reverse ( ) ; int k = 0 , sum = 0 ; for ( int j = 0 ; j < evenArr . Count ; j ++ ) { arr [ k ++ ] = evenArr [ j ] ; arr [ k ++ ] = oddArr [ j ] ; sum += evenArr [ j ] * oddArr [ j ] ; } return sum ; } public static void Main ( ) { int [ ] arr = { 1 , 5 , 8 , 9 , 6 , 7 , 3 , 4 , 2 , 0 } ; int n = arr . Length ; Console . WriteLine ( " Minimum ▁ required ▁ sum ▁ = ▁ " + minSum ( arr , n ) ) ; Console . WriteLine ( " Sorted ▁ array ▁ in ▁ " + " required ▁ format ▁ : ▁ " ) ; for ( int i = 0 ; i < n ; i ++ ) { Console . Write ( arr [ i ] + " ▁ " ) ; } } }