![]() |
VOOZH | about |
We are given an array of even size, we have to sort the array in such a way that the sum of product of alternate elements is minimum also we have to find that minimum sum.
Examples:
Input : arr[] = {9, 2, 8, 4, 5, 7, 6, 0}
Output : Minimum sum of the product of
consecutive pair elements: 74
Sorted arr[] for minimum sum:
{9, 0, 8, 2, 7, 4, 6, 5}
Explanation : We get 74 using below
calculation in rearranged array.
9*0 + 8*2 + 7*4 + 6*5 = 74
Input : arr[] = {1, 2, 1, 4, 0, 5, 6, 0}
Output : Minimum sum of the product of
consecutive pair elements: 6
Sorted arr[] for minimum sum:
{6, 0, 5, 0, 4, 1, 2, 1}
Explanation : We get 6 using below:
6*0 + 5*0 + 4*1 + 2*1 = 6
This problem is a variation of Minimize the sum of product of two arrays with permutations allowed.
For rearranging the array in such a way that we should get the sum of the product of consecutive element pairs is minimum we should have all even index element in decreasing and odd index element in increasing order with all n/2 maximum elements as even indexed and next n/2 elements as odd indexed or vice-versa.
Now, for that our idea is simple, we should sort the main array and further create two auxiliary arrays evenArr[] and oddArr[] respectively. We traverse input array and put n/2 maximum elements in evenArr[] and next n/2 elements in oddArr[]. Then we sort evenArr[] in descending and oddArr[] in ascending order. Finally, copy evenArr[] and oddArr[] element by element to get the required result and should calculate the minimum required sum.
Below is the implementation of above approach :
Minimum required sum = 60 Sorted array in required format : 9 0 8 1 7 2 6 3 5 4
Time Complexity: O(nlog(n))
Auxiliary Space: O(n)