Rearrange an array to minimize sum of product of consecutive pair elements
Last Updated :
19 Sep, 2023
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++
// 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
// 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] + " ");
}
}
}
Python3
# 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
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
JavaScript
<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>
OutputMinimum 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)
Similar Reads
Rearrange array elements to maximize the sum of MEX of all prefix arrays Given an array arr[] of size N, the task is to rearrange the array elements such that the sum of MEX of all prefix arrays is the maximum possible. Note: MEX of a sequence is the minimum non-negative number not present in the sequence. Examples: Input: arr[] = {2, 0, 1}Output: 0, 1, 2Explanation:Sum
7 min read
Maximize product of digit sum of consecutive pairs in a subsequence of length K Given an array of integers arr[], the task is to maximize the product of the digit sum of every consecutive pair in a subsequence of length K.Note: K is always even because pairs will be formed at an even length. Examples: Input: arr[] = {2, 100, 99, 3, 16}, K = 4 Output: 128 The optimal subsequence
12 min read
Minimum sum of product of elements of pairs of the given array Given an array arr[] of even number of element N in it. The task is to form N/2 pairs such that sum of product of elements in those pairs is minimum. Examples Input: arr[] = { 1, 6, 3, 1, 7, 8 } Output: 270 Explanation: The pair formed are {1, 1}, {3, 6}, {7, 8} Product of sum of these pairs = 2 * 9
5 min read
Minimize the sum of MEX by removing all elements of array Given an array of integers arr[] of size N. You can perform the following operation N times: Pick any index i, and remove arr[i] from the array and add MEX(arr[]) i.e., Minimum Excluded of the array arr[] to your total score. Your task is to minimize the total score. Examples: Input: N = 8, arr[] =
7 min read
Minimize cost to reduce array to a single element by replacing K consecutive elements by their sum Given an array arr[] of size N and an integer K, the task is to find the minimum cost required to reduce given array to a single element, where cost of replacing K consecutive array elements by their sum is equal to the sum of the K consecutive elements. If it is not possible to reduce given array t
10 min read