最小化 C++ 中 N 个数字形成的 N/2 个成对数字的平方和
问题陈述
给定一个由 n 个元素组成的数组。这项任务是以这样一种方式创建 n/2 个配对,使得 n/2 个配对的平方和最小。
示例
如果给定的数组是 −
arr[] = {5, 10, 7, 4} then minimum sum of squares is 340 if we create pairs as (4, 10) and ( 5, 7)
算法
1. Sort the array 2. Take two variables which point to start and end index of an array 3. Calulate sum as follows: sum = arr[start] + arr[end]; sum = sum * sum; 4. Repeate this procedure till start < end and increment minSum as follows: While (start < end) { sum = arr[start] + arr[end]; sum = sum * sum; minSum += sum; ++start; --end; }
示例
#include <iostream> #include <algorithm> #define SIZE(arr) (sizeof(arr) / sizeof(arr[0])) using namespace std; int getMinSquareSum(int *arr, int n) { sort(arr, arr + n); int minSum = 0; int start = 0; int end = n - 1; while (start < end) { int sum = arr[start] + arr[end]; sum *= sum; minSum += sum; ++start; --end; } return minSum; } int main() { int arr[] = {5, 10, 7, 4}; int res = getMinSquareSum(arr, SIZE(arr)); cout << "Minimum square sum: " << res << "\n"; return 0; }
输出
当你编译并执行上述程序时。它会生成以下输出 −
Minimum square sum: 340
广告