
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Minimize the sum of squares of sum of N/2 paired formed by N numbers in C++
Problem statement
Given an array of n elements. The task is to create n/2 pairs in such a way that sum of squares of n/2 pairs is minimal.
Example
If given array is −
arr[] = {5, 10, 7, 4} then minimum sum of squares is 340 if we create pairs as (4, 10) and ( 5, 7)
Algorithm
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; }
Example
#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; }
Output
When you compile and execute above program. It generates following output −
Minimum square sum: 340
- Related Articles
- Difference between sum of the squares of and square of sum first n natural numbers.
- Sum of squares of the first n even numbers in C Program
- Sum of squares of first n natural numbers in C Program?
- Python Program for Sum of squares of first n natural numbers
- C++ Program for Sum of squares of first n natural numbers?
- Sum of all subsets of a set formed by first n natural numbers
- Java Program to calculate Sum of squares of first n natural numbers
- Sum of sum of first n natural numbers in C++
- Count pairs (a, b) whose sum of squares is N (a^2 + b^2 = N) in C++
- Sum of the first N Prime numbers
- Minimum number of squares whose sum equals to given number n\n
- Sum of squares of Fibonacci numbers in C++
- Sum of square of first n odd numbers
- Count of numbers satisfying m + sum(m) + sum(sum(m)) = N in C++
- Squared sum of n odd numbers - JavaScript

Advertisements