Minimum sum of product of elements of pairs of the given array
Last Updated :
29 Aug, 2022
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 * 15 = 270
Input: arr[] = {2, 3, 90, 12}
Output: 510
Explanation:
Pairs should be created in this way {2, 3}, {12, 90}
Product of sum of these pairs = 5*112 = 510
Approach:
- Sort the elements in the given array arr[].
- Make pairs of first two-element, then next two-element and so on.
- Calculate the sum of product of corresponding pairs formed.
Below is the implementation of the above approach:
CPP
#include "bits/stdc++.h"
using namespace std;
int minimumProduct( int * arr, int n)
{
sort(arr, arr + n);
int product = 1;
for ( int i = 0; i < n; i += 2) {
product *= (arr[i] + arr[i + 1]);
}
return product;
}
int main()
{
int arr[] = { 1, 6, 3, 1, 7, 8 };
int n = sizeof (arr) / sizeof (arr[0]);
cout << minimumProduct(arr, n) << endl;
return 0;
}
|
Java
import java.util.*;
class GFG{
static int minimumProduct( int [] arr, int n)
{
Arrays.sort(arr);
int product = 1 ;
for ( int i = 0 ; i < n; i += 2 ) {
product *= (arr[i] + arr[i + 1 ]);
}
return product;
}
public static void main(String[] args)
{
int arr[] = { 1 , 6 , 3 , 1 , 7 , 8 };
int n = arr.length;
System.out.print(minimumProduct(arr, n) + "\n" );
}
}
|
Python3
def minimumProduct(arr, n):
arr = sorted (arr)
product = 1
for i in range ( 0 , n, 2 ):
product * = (arr[i] + arr[i + 1 ])
return product
arr = [ 1 , 6 , 3 , 1 , 7 , 8 ]
n = len (arr)
print (minimumProduct(arr, n))
|
C#
using System;
class GFG {
static int minimumProduct( int [] arr, int n)
{
Array.Sort(arr);
int product = 1;
for ( int i = 0; i < n; i += 2) {
product *= (arr[i] + arr[i + 1]);
}
return product;
}
static void Main()
{
int [] arr = new int [] { 1, 6, 3, 1, 7, 8 };
int n = arr.Length;
Console.Write(minimumProduct(arr, n));
}
}
|
Javascript
<script>
function minimumProduct(arr, n)
{
arr.sort();
let product = 1;
for (let i = 0; i < n; i += 2) {
product *= (arr[i] + arr[i + 1]);
}
return product;
}
let arr = [ 1, 6, 3, 1, 7, 8 ];
let n = arr.length;
document.write(minimumProduct(arr, n) + "<br>" );
</script>
|
Time Complexity: O(N*log N) the inbuilt sort function takes N log N time to complete all operations, hence the overall time taken by the algorithm is N log N
Auxiliary Space: O(1) since no extra array is used so the space taken by the algorithm is constant
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...