给定N个数字(N是偶数)。将N个数分成N / 2对,以使成对的数之和的平方和最小。任务是打印最小金额。
例子:
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
方法:任务是使平方和最小,因此我们将第一组中的最小和最大数除以第二组中的第二最小和第二大数,依此类推,直到形成N / 2组。将数字相加并存储它们的平方和,这将是最终答案。
下面是上述方法的实现:
C++
// C++ program to minimize the sum
// of squares of sum of numbers
// of N/2 groups of N numbers
#include
using namespace std;
// Function that returns the minimize sum
// of square of sum of numbers of every group
int findMinimal(int a[], int n)
{
// Sort the array elements
sort(a, a + n);
int sum = 0;
// Iterate for the first half of array
for (int i = 0; i < n / 2; i++)
sum += (a[i] + a[n - i - 1])
* (a[i] + a[n - i - 1]);
return sum;
}
// Driver Code
int main()
{
int a[] = { 8, 5, 2, 3 };
int n = sizeof(a) / sizeof(a[0]);
cout << findMinimal(a, n);
return 0;
}
Java
// Java program to minimize the sum
// of squares of sum of numbers
// of N/2 groups of N numbers
import java.util.Arrays;
class GFG
{
// Function that returns the minimize sum
// of square of sum of numbers of every group
static int findMinimal(int []a, int n)
{
// Sort the array elements
Arrays.sort(a);
int sum = 0;
// Iterate for the first half of array
for (int i = 0; i < n / 2; i++)
sum += (a[i] + a[n - i - 1]) *
(a[i] + a[n - i - 1]);
return sum;
}
// Driver Code
public static void main(String str[])
{
int []a = { 8, 5, 2, 3 };
int n = a.length;
System.out.println(findMinimal(a, n));
}
}
// This code is contributed by Ryuga
Python 3
# Python 3 program to minimize the sum
# of squares of sum of numbers
# of N/2 groups of N numbers
# Function that returns the minimize sum
# of square of sum of numbers of every group
def findMinimal(a, n):
# Sort the array elements
a.sort()
sum = 0
# Iterate for the first half of array
for i in range( n // 2):
sum += ((a[i] + a[n - i - 1]) *
(a[i] + a[n - i - 1]))
return sum
# Driver Code
if __name__ == "__main__":
a = [ 8, 5, 2, 3 ]
n = len(a)
print(findMinimal(a, n))
# This code is contributed by ita_c
C#
// C# program to minimize the sum
// of squares of sum of numbers
// of N/2 groups of N numbers
using System;
class GFG
{
// Function that returns the minimize sum
// of square of sum of numbers of every group
static int findMinimal(int []a, int n)
{
// Sort the array elements
Array.Sort(a);
int sum = 0;
// Iterate for the first half of array
for (int i = 0; i < n / 2; i++)
sum += (a[i] + a[n - i - 1]) *
(a[i] + a[n - i - 1]);
return sum;
}
// Driver Code
public static void Main()
{
int []a = { 8, 5, 2, 3 };
int n = a.Length;
Console.Write(findMinimal(a, n));
}
}
// This code is contributed
// by Akanksha Rai
PHP
Javascript
输出:
164
时间复杂度: O(N log N)
辅助空间: O(N)