text: Rearrange an array to minimize sum of product of consecutive pair elements | C ++ 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
code: #include <bits/stdc++.h> NEW_LINE using namespace std ; int minSum ( int arr [ ] , int n ) { vector < int > evenArr ; vector < int > oddArr ; sort ( arr , arr + n ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( i < n / 2 ) oddArr . push_back ( arr [ i ] ) ; else evenArr . push_back ( arr [ i ] ) ; } sort ( evenArr . begin ( ) , evenArr . end ( ) , greater < int > ( ) ) ; int i = 0 , sum = 0 ; for ( int j = 0 ; j < evenArr . size ( ) ; j ++ ) { arr [ i ++ ] = evenArr [ j ] ; arr [ i ++ ] = oddArr [ j ] ; sum += evenArr [ j ] * oddArr [ j ] ; } return sum ; } int main ( ) { int arr [ ] = { 1 , 5 , 8 , 9 , 6 , 7 , 3 , 4 , 2 , 0 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << " Minimum ▁ required ▁ sum ▁ = ▁ " << minSum ( arr , n ) ; cout << " Sorted array in required format : " ; for ( int i = 0 ; i < n ; i ++ ) cout << arr [ i ] << " ▁ " ; return 0 ; }