Open In App

Rearrange an array to minimize sum of product of consecutive pair elements

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 :




// C++ program to sort an array such that
// sum of product of alternate element
// is minimum.
#include <bits/stdc++.h>
using namespace std;
  
int minSum(int arr[], int n)
{
    // create evenArr[] and oddArr[]
    vector<int> evenArr;
    vector<int> oddArr;
  
    // sort main array in ascending order
    sort(arr, arr+n );
  
    // Put elements in oddArr[] and evenArr[]
    // as per desired value.
    for (int i = 0; i < n; i++)
    {
        if (i < n/2)
            oddArr.push_back(arr[i]);
        else
            evenArr.push_back(arr[i]);
    }
  
    // sort evenArr[] in descending order
    sort(evenArr.begin(), evenArr.end(), greater<int>());
  
    // merge both sub-array and
    // calculate minimum sum of
    // product of alternate elements
    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;
}
  
// Driver Program
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 << "\nSorted array in required format : ";
    for (int i=0; i<n; i++)
       cout << arr[i] << " ";
    return 0;
}




// Java program to sort an array such that 
// sum of product of alternate element 
// is minimum. 
  
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Vector;
  
class GFG {
  
    static int minSum(int arr[], int n) {
        // create evenArr[] and oddArr[] 
        Vector<Integer> evenArr = new Vector<>();
        Vector<Integer> oddArr = new Vector<>();
  
        // sort main array in ascending order 
        Arrays.sort(arr);
  
        // Put elements in oddArr[] and evenArr[] 
        // as per desired value. 
        for (int i = 0; i < n; i++) {
            if (i < n / 2) {
                oddArr.add(arr[i]);
            } else {
                evenArr.add(arr[i]);
            }
        }
  
        // sort evenArr[] in descending order
        Comparator comparator = Collections.reverseOrder();
        Collections.sort(evenArr,comparator);
  
        // merge both sub-array and 
        // calculate minimum sum of 
        // product of alternate elements 
        int i = 0, sum = 0;
        for (int j = 0; j < evenArr.size(); j++) {
            arr[i++] = evenArr.get(j);
            arr[i++] = oddArr.get(j);
            sum += evenArr.get(j) * oddArr.get(j);
        }
  
        return sum;
    }
  
// Driver program 
    public static void main(String[] args) {
  
        int arr[] = {1, 5, 8, 9, 6, 7, 3, 4, 2, 0};
        int n = arr.length;
        System.out.println("Minimum required sum = " 
                                  + minSum(arr, n));
        System.out.println("Sorted array in required format : ");
        for (int i = 0; i < n; i++) {
            System.out.print(arr[i] + " ");
        }
  
    }
  
}




# Python 3 program to sort an array such 
# that sum of product of alternate element
# is minimum.
def minSum(arr, n):
  
    # create evenArr[] and oddArr[]
    evenArr = []
    oddArr = []
  
    # sort main array in ascending order
    arr.sort()
  
    # Put elements in oddArr[] and 
    # evenArr[] as per desired value.
    for i in range(n):
      
        if (i < n // 2):
            oddArr.append(arr[i])
        else:
            evenArr.append(arr[i])
  
    # sort evenArr[] in descending order
    evenArr.sort(reverse = True)
  
    # merge both sub-array and
    # calculate minimum sum of
    # product of alternate elements
    i = 0
    sum = 0
    for j in range(len(evenArr)):
        arr[i] = evenArr[j]
        i += 1
        arr[i] = oddArr[j]
        i += 1
        sum += evenArr[j] * oddArr[j]
      
    return sum
  
# Driver Code
if __name__ == "__main__":
      
    arr = [ 1, 5, 8, 9, 6, 7, 3, 4, 2, 0 ]
    n = len(arr)
    print( "Minimum required sum ="
                      minSum(arr, n))
    print("Sorted array in required format : "
                                      end = "")
    for i in range(n):
        print(arr[i], end = " ")
  
# This code is contributed by ita_c




// Program to sort an array such that 
// sum of product of alternate element 
// is minimum. 
using System;
using System.Collections.Generic;
  
class GFG
{
static int minSum(int []arr, int n) 
{
    // create evenArr[] and oddArr[] 
    List<int> evenArr = new List<int>();
    List<int> oddArr = new List<int>();
    int i;
      
    // sort main array in ascending order 
    Array.Sort(arr);
  
    // Put elements in oddArr[] and 
    // evenArr[] as per desired value. 
    for (i = 0; i < n; i++) 
    {
        if (i < n / 2) 
        {
            oddArr.Add(arr[i]);
        
        else 
        {
            evenArr.Add(arr[i]);
        }
    }
  
    // sort evenArr[] in descending order
    evenArr.Sort();
    evenArr.Reverse();
  
    // merge both sub-array and 
    // calculate minimum sum of 
    // product of alternate elements 
    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;
}
  
// Driver Code 
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] + " ");
    }
}
}
  
// This code contributed by 29AjayKumar




<script>
  
// Javascript program to sort an array such that 
// sum of product of alternate element 
// is minimum. 
  
    function minSum(arr,n)
    {
        // create evenArr[] and oddArr[] 
        let evenArr =[];
        let oddArr = [];
          
        // sort main array in ascending order 
        arr.sort(function(a,b){return a-b;});
          
        // Put elements in oddArr[] and evenArr[] 
        // as per desired value.
        for (let i = 0; i < n; i++) {
            if (i < Math.floor(n / 2)) {
                oddArr.push(arr[i]);
            } else {
                evenArr.push(arr[i]);
            }
        }
          
        // sort evenArr[] in descending order
        evenArr.sort(function(a,b){return b-a;});
          
        // merge both sub-array and 
        // calculate minimum sum of 
        // product of alternate elements 
        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;
    }
      
    // Driver program 
    let arr=[1, 5, 8, 9, 6, 7, 3, 4, 2, 0];
    let n = arr.length;
    document.write("Minimum required sum = " 
                                  + minSum(arr, n)+"<br>");
      
    document.write("Sorted array in required format : ");
    for (let i = 0; i < n; i++) {
        document.write(arr[i] + " ");
    }
      
    // This code is contributed by avanitrachhadiya2155
      
</script>

Output
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)

 


Article Tags :