Rearrange an array to minimize sum of product of consecutive pair elements | Python 3 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
def minSum ( arr , n ) : NEW_LINE INDENT evenArr = [ ] NEW_LINE oddArr = [ ] NEW_LINE arr . sort ( ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( i < n // 2 ) : NEW_LINE INDENT oddArr . append ( arr [ i ] ) NEW_LINE DEDENT else : NEW_LINE INDENT evenArr . append ( arr [ i ] ) NEW_LINE DEDENT DEDENT evenArr . sort ( reverse = True ) NEW_LINE i = 0 NEW_LINE sum = 0 NEW_LINE for j in range ( len ( evenArr ) ) : NEW_LINE INDENT arr [ i ] = evenArr [ j ] NEW_LINE i += 1 NEW_LINE arr [ i ] = oddArr [ j ] NEW_LINE i += 1 NEW_LINE sum += evenArr [ j ] * oddArr [ j ] NEW_LINE DEDENT return sum NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 5 , 8 , 9 , 6 , 7 , 3 , 4 , 2 , 0 ] NEW_LINE n = len ( arr ) NEW_LINE print ( " Minimum ▁ required ▁ sum ▁ = " , minSum ( arr , n ) ) NEW_LINE print ( " Sorted ▁ array ▁ in ▁ required ▁ format ▁ : ▁ " , end = " " ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT print ( arr [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT