Minimize the sum of squares of sum of N/2 paired formed by N numbers
Last Updated :
16 Sep, 2022
Given N numbers(N is an even number). Divide the N numbers into N/2 pairs in such a way that the sum of squares of the sum of numbers in pairs is minimal. The task is to print the minimal sum.
Examples:
Input: a[] = {8, 5, 2, 3}
Output: 164
Divide them into two groups of {2, 8} and {3, 5}
to give (2+8)2 + (3+5)2 = 164
Input: a[] = {1, 1, 1, 2, 2, 2}
Output: 27
Approach: The task is to minimize the sum of squares, hence we divide the smallest and largest number in the first group and the second smallest and second largest in the second group, and so on till N/2 groups are formed. Add the numbers and store the sum of squares of them which will be the final answer.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int findMinimal( int a[], int n)
{
sort(a, a + n);
int sum = 0;
for ( int i = 0; i < n / 2; i++)
sum += (a[i] + a[n - i - 1])
* (a[i] + a[n - i - 1]);
return sum;
}
int main()
{
int a[] = { 8, 5, 2, 3 };
int n = sizeof (a) / sizeof (a[0]);
cout << findMinimal(a, n);
return 0;
}
|
Java
import java.util.Arrays;
class GFG
{
static int findMinimal( int []a, int n)
{
Arrays.sort(a);
int sum = 0 ;
for ( int i = 0 ; i < n / 2 ; i++)
sum += (a[i] + a[n - i - 1 ]) *
(a[i] + a[n - i - 1 ]);
return sum;
}
public static void main(String str[])
{
int []a = { 8 , 5 , 2 , 3 };
int n = a.length;
System.out.println(findMinimal(a, n));
}
}
|
Python 3
def findMinimal(a, n):
a.sort()
sum = 0
for i in range ( n / / 2 ):
sum + = ((a[i] + a[n - i - 1 ]) *
(a[i] + a[n - i - 1 ]))
return sum
if __name__ = = "__main__" :
a = [ 8 , 5 , 2 , 3 ]
n = len (a)
print (findMinimal(a, n))
|
C#
using System;
class GFG
{
static int findMinimal( int []a, int n)
{
Array.Sort(a);
int sum = 0;
for ( int i = 0; i < n / 2; i++)
sum += (a[i] + a[n - i - 1]) *
(a[i] + a[n - i - 1]);
return sum;
}
public static void Main()
{
int []a = { 8, 5, 2, 3 };
int n = a.Length;
Console.Write(findMinimal(a, n));
}
}
|
PHP
<?php
function findMinimal( $a , $n )
{
sort( $a );
$sum = 0;
for ( $i = 0; $i < $n / 2; $i ++)
$sum += ( $a [ $i ] + $a [ $n - $i - 1]) *
( $a [ $i ] + $a [ $n - $i - 1]);
return $sum ;
}
$a = array (8, 5, 2, 3 );
$n = sizeof( $a );
echo findMinimal( $a , $n );
?>
|
Javascript
<script>
function findMinimal(a, n)
{
a.sort();
let sum = 0;
for (let i = 0; i < n / 2; i++)
sum += (a[i] + a[n - i - 1]) *
(a[i] + a[n - i - 1]);
return sum;
}
let a = [8,5,2,3];
let n = a.length;
document.write( findMinimal(a, n));
</script>
|
Complexity Analysis:
- Time Complexity: O(N*logN), as we are using an inbuilt sort function that will cost N*logN time. Where N is the number of elements in the array.
- Auxiliary Space: O(1), as we are not using any extra space.
Share your thoughts in the comments
Please Login to comment...